Home  >  Q&A  >  body text

Help me figure out what's wrong with this bubble sort.

<?php
$arr=array(10,3,1,8);

function bubble(&$arr){
    $total=count($arr);
    for($i=0;$i<$total - 1;$i++){
        for($j=0;$total - 1 - $i;$j++){
            if($arr[$j] > $arr[$j + 1]){
                $temp=$arr[$j];
                $arr[$j]=$arr[$j+1];
                $arr[$j+1]=$temp;
            }
        }
        echo '<br>';
    }
}
bubble($arr);
echo '<br>';
print_r($arr);
?>

HUNTHUNT2588 days ago950

reply all(2)I'll reply

  • 风豆丁

    风豆丁2017-08-23 22:32:56

    The intermediate conditional statement of the second for loop should be $j < $total - 1 - $i

    reply
    2
  • PHP中文网

    PHP中文网2017-08-23 15:54:12

    I have not studied the PHP sorting algorithm. You can use the PHP sorting functions sort, asort, rsort, krsort, and ksort to sort arrays, which is simpler.

    reply
    0
  • Cancelreply