Home > php教程 > php手册 > 简单的一个php 冒泡排序算法

简单的一个php 冒泡排序算法

WBOY
Release: 2016-06-13 10:03:49
Original
922 people have browsed it

在我们刚学编程就知道各种排序算法,现在我们再次看看php 冒泡算法在实际应用中用法吧,有需要的朋友简单的参考一下。

 代码如下 复制代码

header('Content-Type: text/html; charset=utf-8');
//   简单冒泡算法      0 1 2 3 4
$a = array(5,4,3,2,1);  //5
echo  "比较54321  


";
function  mp($a){  //传值 要是数组
        //i=1 i         for($i=0;$i                 /* j=3 j                  * 这里为什么要-2呢
                 * 因为数组是从0开始的 所以要-1
                 * 然后 一会要比较后一位 和倒数第二位  所以 要-2
                 * 当然 -1  也可以 只要把 $a[j+1]改成$a[j]  然后把$a[j] 改成$a[j-1] 即可
                 */
                for ($j=count($a)-2;$j>=$i;$j--){ 
                        //判断数组最大的位数  和第二大的相比
                         if ($a[$j+1]                                  echo  $a[$j+1],'------小于-----',$a[$j],'----------排列前:',fn($a);
               //如果最大的小于第二大的就换位置
                                 $tmp = $a[$j+1];  
                                   $a[$j+1]=$a[$j];
                                   $a[$j]=$tmp;
                                   echo '------------排列后:',fn($a),'

';
                         }
                        
                }
               
               
        }
        return $a;
}

echo  fn(mp($a));


function fn($arr){
        foreach ($arr as $value){
                echo  $value;
        }       
}

   
?>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template