PHP实现四种排序

Posted MeetU

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP实现四种排序相关的知识,希望对你有一定的参考价值。

程序=算法+数据结构,作为一个php程序员,需要掌握一下。

/**
*    冒泡排序
*    按照两两比较大小,注意比较轮数和每轮比较次数;
*    假设数组有n个元素,则需要n-1轮比较;每i轮比较n-i次(即 第1轮中需要n-1次比较、第2轮中需要n-2次比较...第n-1轮中需要1次比较)
*/
function numSort($arr){
    $mnt = count($arr);
    if($mnt==1){
        return $arr;
    }
    for ($i=0; $i < $mnt-1; $i++) { 
        for ($j=0; $j < $mnt-1-$i; $j++) { 
            if($arr[$j]>$arr[$j+1]){
                $temp      = $arr[$j];
                $arr[$j]   = $arr[$j+1];
                $arr[$j+1] = $temp;
            }
        }
    }
    return $arr;
}
//测试
$arr = [5,2,1,1,3,1,4];
$end = numSort($arr);
echo "<pre>";
print_r($end);

过程分析:

第1轮:

第1次: Array ( [0] => 2 [1] => 5 [2] => 1 [3] => 1 [4] => 3 [5] => 1 [6] => 4 )
第2次: Array ( [0] => 2 [1] => 1 [2] => 5 [3] => 1 [4] => 3 [5] => 1 [6] => 4 )
第3次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 5 [4] => 3 [5] => 1 [6] => 4 )
第4次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 5 [5] => 1 [6] => 4 )
第5次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 1 [5] => 5 [6] => 4 )
第6次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )

第2轮:

第1次: Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )
第2次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )
第3次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )
第4次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )
第5次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )

第3轮:

第1次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )
第2次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )
第3次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
第4次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

第4轮:

第1次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
第2次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
第3次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

第5轮:

第1次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
第2次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

第6轮:

第1次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

结论:

假设数组有n个元素,则需要n-1轮比较;每i轮比较n-i次(即 第1轮中需要n-1次比较、第2轮中需要n-2次比较...第n-1轮中需要1次比较)
















以上是关于PHP实现四种排序的主要内容,如果未能解决你的问题,请参考以下文章

PHP实现四种基本排序算法

php 四种基础算法 ---- 选择排序法

PHP实现四种基本排序算法

PHP实现四种基本排序算法

PHP实现四种排序

php实现插入排序的代码示例