代码实现:
/**
* 插入排序
* 在要排序的一组数中,假设前面的数已经是排好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数也是排好顺序的。如此反复循环,直到全部排好顺序。
*/
function insertSort($arr) {
$len=count($arr);
//这个元素 就是从第二个元素开始,到最后一个元素都是这个需要排序的元素
for($i=1;$i<$len; $i++) {
$tmp = $arr[$i];
//内层循环控制,比较并插入
for($j=$i-1;$j>=0;$j--) {
if($tmp < $arr[$j]) {
//发现插入的元素要小,交换位置,将后边的元素与前面的元素互换
$arr[$j+1] = $arr[$j];
$arr[$j] = $tmp;
} else {
//如果碰到不需要移动的元素,由于是已经排序好是数组,则前面的就不需要再次比较了。
break;
}
}
}
return $arr;
}
//测试
$arr = [5,2,1,1,3,1,4];
// $arr = [5,2,0,0];
$end = insertSort($arr);
echo "<pre>";
print_r($end);
过程分析:
第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 )
Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 1 [4] => 3 [5] => 1 [6] => 4 )
第3轮
Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 5 [4] => 3 [5] => 1 [6] => 4 )
Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 5 [4] => 3 [5] => 1 [6] => 4 )
第4轮
Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 5 [5] => 1 [6] => 4 )
第5轮
Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => 5 [6] => 4 )
Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 5 [6] => 4 )
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 5 [6] => 4 )
第6轮
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
|
请发表评论