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次比较)

posted @ 2019-02-20 16:56  MeetU  阅读(302)  评论(0编辑  收藏  举报