冒泡排序函数

<?php

//冒泡排序函数
//本函数使用引用是为了避免不必要的内存消耗
function &bubble(&$arr){
    $count=count($arr);
    if($count>1){
        for($i=0;$i<$count;$i++){
            for($j=$count-1;$j>=$i;$j--){
                if($arr[$j-1]>$arr[$j]){
                    $temp=$arr[$j-1];
                    $arr[$j-1]=$arr[$j];
                    $arr[$j]=$temp;
                }  
            }  
        }  
    }
    return $arr;
}
  
//输出数组(方便网页上查看)
function printArr(&$arr){
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}

//开始测试
//给数组随机赋十个数值
for($i=0;$i<10;$i++){
    $testArr[]=rand(10,100);
}

printArr(bubble($testArr));

?>

另外一种写法

<?php

$array = array(5, 4, 9, 20, 2, 7, 10, 17, 15 ,16 ,23);

$count = count($array);
for($i = 0; $i < $count; $i++){
for($j = $count-1; $j >= $i+1; $j--){
if($array[$j] < $array[$j-1]){
list($array[$j], $array[$j-1]) = array($array[$j-1], $array[$j]);
}
}
}

print($array);

?>

  

  深入理解冒泡算法:视屏

http://www.tudou.com/programs/view/wR9yXZfGr0c/

原文地址:https://www.cnblogs.com/EasonSun/p/2960564.html