Bubble Sort Algorithm Help


#1

I am trying to sort an array of numbers using the Bubble Sort Algorithm. Is my Code correct? any feedback would be appreciated.

[php]

<?php $list = array(99,10,9,6,7,12); //print_r ($list); $arr_length = count($list); // Bubble sort algorithm for ($i =0; $i < $arr_length; $i++) { for ($j=0; $j < $arr_length; $j++) { $left_val = $list[$j]; if ($j < $arr_length - 1 ) { $right_val= $list[$j + 1]; if ($left_val > $right_val) { $list[$j] = $right_val; $list[$j + 1] = $left_val; } } } $arr_length = $arr_length - 1; //print_r($list); //echo $arr_length; } // Print list of numnbers to be sorted for ($x=0; $x < count($list); $x++) { echo $list[$x]; if ($x < count($list) - 1) { echo " , "; } } ?>

[/php]

Thank you.
Cheers.
Tony


#2

Tonyb, is this for a class project? We don’t want to do your homework for you.

Now, with that said, in PHP, for single arrays there is already a sort function. You would do better just to use it.
There are times when a “bubble-sort” is needed for nested arrays, meaning muli-dimensional arrays, but, for
the array you showed, it is not needed.
[php]
$list = array(99,10,9,6,7,12);
sort($list);
[/php]

Hope that helps!