zoukankan      html  css  js  c++  java
  • 冒泡排序函数

    <?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/

  • 相关阅读:
    数据类型
    一些骚操作
    re
    多任务
    监听按钮点击事件
    监听按钮点击事件
    监听按钮点击事件
    将博客搬至博客园
    将博客搬至博客园
    将博客搬至博客园
  • 原文地址:https://www.cnblogs.com/EasonSun/p/2960564.html
Copyright © 2011-2022 走看看