Can someone give me a run down of each part of this script please


I am new to PHP and would be extremely grateful if someone could check my comments on this bubblesort script. I looked around the net and found the framework for this script and adjusted it to suit me and to get an understanding but need help with a clearer explanation for the part highlighted in green.

<?php // Create the array$numbers = array(16,32,22,15,12,44,31,67,96,54); // Count the size of the array via $numbers$array_size = count($numbers); // Below defines a loop that starts with i=1. The loop will continue to run as long as 'i' is less than $array_size. 'i' will increase by 1 // each time the loop runs. It will then echo the array using 'i' as the key. echo " Numbers before Sort"; for ( $i = 0; $i < $array_size; $i++ ) echo " ". $numbers[$i] ."\n"; // Sets $i and $j as variables which are less than the array size and are incremented on each cycle. for ( $i = 0; $i < $array_size; $i++ ) { for ($j = 0; $j < $array_size; $j++ ) { //Takes the array with variables $i and $j used a skeys to move through the array checking if $names[$i] is less than $names[$j]. if ($numbers[$i] < $numbers[$j]) { $temp = $numbers[$i]; $numbers[$i] = $numbers[$j]; $numbers[$j] = $temp; } } } // Sorts through the new $numbers variable and echo's it on screen. echo " Numbers after sort"; for( $i = 0; $i < $array_size; $i++ ) echo " ". $numbers[$i] ."\n"; ?>

Kind regards and thank you in advance.

You could say instead

// Loop through the array n*n times
for ( $i = 0; $i < $array_size; $i++ )
for ($j = 0; $j < $array_size; $j++ )
// Swap adjacent items that are out of order.
if ($numbers[$i] < $numbers[$j])
$temp = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $temp;

Many thank for your reply. :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service