Search code examples
phpalgorithmsortingbubble-sort

Sorting an array with bubble sort


I am trying to create an algorithm that shows each step of bubble sort, sorting one number at a time. I was was able to sort the number at the first index, but I need to figure out how to sort all the numbers.

$x = array (9,7,5,3,0);

$count = count($x);
for($i = 0; $i < $count-1; $i++ ) {
    $temp = $x[$i+1];
    $x[$i+1] = $x[$i];
    $x[$i] = $temp;
    echo '<pre>';
    print_r($x);
}

My current output is:

Array
(
    [0] => 7
    [1] => 9
    [2] => 5
    [3] => 3
    [4] => 0
)
Array
(
    [0] => 7
    [1] => 5
    [2] => 9
    [3] => 3
    [4] => 0
)
Array
(
    [0] => 7
    [1] => 5
    [2] => 3
    [3] => 9
    [4] => 0
)
Array
(
    [0] => 7
    [1] => 5
    [2] => 3
    [3] => 0
    [4] => 9
)

From here I need to continue sorting the remaining numbers. For 7, the output should be

57390
53790
53970
53907

and then for 3

35079
30579
30759
30795

and then for 0, it should be same for all 4 lines like

03570
03579
03579
03579

[The assigned problem.][1]


Solution

  • Two issues:

    • You should only swap values when they are not in the right order
    • You need an outer loop to repeat this inner loop, similar to a proper bubble sort algorithm.

    Your code can be modified like below so it generates the required output:

    $x = array (9,7,5,3,0);
    
    $count = count($x) - 1;
    for($times = 0; $times < $count; $times++) {
        for($i = 0; $i < $count; $i++ ) {
            $temp = $x[$i+1];
            if ($temp < $x[$i]) {
                $x[$i+1] = $x[$i];
                $x[$i] = $temp;
            }
            echo implode(" ", $x) . "\n";
        }
        echo "\n";
    }
    

    Note that a proper bubble sort algorithm will perform fewer iterations.