您的位置:首页 > 编程语言 > PHP开发

PHP排序算法:插入排序 (一维数组)

2016-07-19 00:00 543 查看
摘要: PHP插入排序算法实现

时间复杂度

最优时间复杂度:O(n) (升序排列,序列已经处于升序状态)

最坏时间复杂度:O(n2)

稳定性:稳定

原理与实现:



遍历数组,每次把一个待排序的元素,插入到前面已经排好序的数列中的恰当位置,使数列依然有序。知道待排序的元素全部插入完为止。就得到了一个排序号的数组。

$array = [34,23,4,7,13,43,6,12,56,2];


$toSort == 1时: [23, 34 , 4 , 7 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 2时: [4 , 23 , 34 , 7 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 3时: [4 , 7 , 23 , 34 , 13 , 43 , 6 , 12 , 56 , 2]
$toSort == 4时: [4 , 7 , 13 , 23 , 34 , 43 , 6 , 12 , 56 , 2]
$toSort == 5时: [4 , 7 , 13 , 23 , 34 , 43 , 6 , 12 , 56 , 2]
$toSort == 6时: [4 , 6 , 7 , 13 , 23 , 34 , 43 , 12 , 56 , 2]
$toSort == 7时: [4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56 , 2]
$toSort == 8时: [4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56 , 2]
$toSort == 9时: [2 , 4 , 6 , 7 , 12 , 13 , 23 , 34 , 43 , 56]

$count = count($array);

for($toSort = 1;$toSort < $count;$toSort++){
//当前要插入的值
$insert = $array[$toSort];
for($sorted = $toSort - 1;$sorted >= 0;$sorted--){
//待插入元素比已排好序的要小,换位
if($insert < $array[$sorted]){
$array[$sorted + 1] = $array[$sorted];
$array[$sorted] = $insert;
//待插入前面的已经是排好序的,就不用比较换位了
}else{
break;
}
}
}

print_r($array);

输出

Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 7 [4] => 12 [5] => 13 [6] => 23 [7] => 34 [8] => 43 [9] => 56 )
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: