0

I have some problems with PHP right now. I don't know how to create a code which sorts numbers in array from lowest to highest (and contrariwise). I'm only allowed to use loops and conditions without using PHP built-in functions, so I can understand how these functions work.

I found this code on Stack overflow sorting array value without using built in php like sort() etc:

<?php

$array=array('2','4','8','5','1','7','6','9','10','3');

echo "Unsorted array is: ";
echo "<br />";
print_r($array);


for($j = 0; $j < count($array); $j ++) {
    for($i = 0; $i < count($array)-1; $i ++){

        if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }       
    }
}

echo "Sorted Array is: ";
echo "<br />";
print_r($array);

?>

Can someone please explain step by step on each line how part of the code below works? I lose concentration when trying to understand this.

for($j = 0; $j < count($array); $j ++) {
        for($i = 0; $i < count($array)-1; $i ++){

            if($array[$i] > $array[$i+1]) {
                $temp = $array[$i+1];
                $array[$i+1]=$array[$i];
                $array[$i]=$temp;
            }       
        }
    } 
Community
  • 1
  • 1
encrypted21
  • 194
  • 11
  • 1
    it is called "bubble sort": https://en.wikipedia.org/wiki/Bubble_sort – Crypt32 Feb 21 '16 at 11:24
  • 1
    Please note that it's generally a bad idea to put `count` into `for` loop, as it slows the iterations dramatically. Instead, put `count` into a separate variable and that variable into the `for` loop. – Kevin Kopf Feb 21 '16 at 11:34

3 Answers3

1

Your code looks like a worsened variant of Bubble Sort:

let `$n` be `count($array)` for simplicity
for $n times
    go through each element in the array and compare to the next one
    if it is larger than the next one, swap the elements (swap is done using a temporary variable $temp)

This swapping ensures the after each step the largest elements will go through the end of the array (fist iteration ensures that the largest element is the last one, the second largest is has the place before the last), so a first optimization would be to iterate on element less ($i < n becomes $i < $n - $j).

Another optimization is to check if any swapping was performed in the current loop ($j loop). No swapping means that the array is ordered and the algorithm can be terminated.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
1

@Alexei is right, it's a simple bubble sort variant. Maybe it'll help you to visualize what's going on:

<?php

$array=array('2','4','8','5','1','7','6','9','10','3');

dump_array($array, 0);

for($j = 0; $j < count($array); $j ++) {
    for($i = 0; $i < count($array)-1; $i ++){

        if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }       
    }
    dump_array($array, $j+1);
}

function dump_array($array, $step) {
    foreach($array as $num) {
        echo sprintf("%02d", $num) . ", ";
    }
    echo " step $step ($step largest elements reached end of array)\n";
}
?>

Output:

02, 04, 08, 05, 01, 07, 06, 09, 10, 03,  step 0 (0 largest elements reached end of array)
02, 04, 05, 01, 07, 06, 08, 09, 03, 10,  step 1 (1 largest elements reached end of array)
02, 04, 01, 05, 06, 07, 08, 03, 09, 10,  step 2 (2 largest elements reached end of array)
02, 01, 04, 05, 06, 07, 03, 08, 09, 10,  step 3 (3 largest elements reached end of array)
01, 02, 04, 05, 06, 03, 07, 08, 09, 10,  step 4 (4 largest elements reached end of array)
01, 02, 04, 05, 03, 06, 07, 08, 09, 10,  step 5 (5 largest elements reached end of array)
01, 02, 04, 03, 05, 06, 07, 08, 09, 10,  step 6 (6 largest elements reached end of array)
01, 02, 03, 04, 05, 06, 07, 08, 09, 10,  step 7 (7 largest elements reached end of array)
01, 02, 03, 04, 05, 06, 07, 08, 09, 10,  step 8 (8 largest elements reached end of array)
01, 02, 03, 04, 05, 06, 07, 08, 09, 10,  step 9 (9 largest elements reached end of array)
01, 02, 03, 04, 05, 06, 07, 08, 09, 10,  step 10 (10 largest elements reached end of array)

One more comment. This is where values get swapped:

// Swap one element ($i) with it's successor ($i+1)
if($array[$i] > $array[$i+1]) {
  // We need a temporary var to store $array[$i+1]
  $temp = $array[$i+1];
  // Now that $array[$i+1] is stored, we can overwrite it with $array[$i]
  $array[$i+1]=$array[$i];
  // Use stored value to overwrite $array[$i]
  $array[$i]=$temp;
  // Now both values got swapped
}       
maxhb
  • 8,554
  • 9
  • 29
  • 53
1

Just relax. :) This is one of the easiest code.

In your code:

<?php

$array=array('2','4','8','5','1','7','6','9','10','3');

//array declared with members

echo "Unsorted array is: ";
echo "<br />";
print_r($array);

//will output the present condition of your array

for($j = 0; $j < count($array); $j ++) {

//this is the first for loop. here, count($array) will return 10 as you have 10 members inside your array. So simply it just for($j = 0; $j < 10; $j ++). This for will loop through 0-9.

for($i = 0; $i < count($array)-1; $i ++){

//this is the second for loop. here, count($array)-1 will return 9. So simply it just for($i = 0; $i < 9; $i ++). This for will loop through 0-8.

    if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }       
    }
}

//this is the main part of your code. It check if a array member is greater than it's next member. If so then it swap the position or the code continue as there is no "else" statement. Suppose value of i is 0. Then if($array[0] > $array[1])->if(2>4) answer is no, so the code continue. Suppose value of i is 2. Then if($array[2] > $array[3])->if(8>5) answer is yes, now just swapping position happen. $temp=5 then $array[3]=$array[2] then $array[2]=5.

echo "Sorted Array is: ";
echo "<br />";
print_r($array);

?>

//just print the sorted array.