插入排序
基本思路:
每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的数据序列的适当位置,直到全部记录插入完成为止
图示:
代码:
//插入排序 function insertSort($arr) { $count = count($arr); for ($i = 1; $i < $count; $i++) { $temp = $arr[$i]; for ($j = $i-1; $j >= 0; $j--) { if($arr[$j] > $temp) { $arr[$j+1] = $arr[$j]; $arr[$j] = $temp; } } } return $arr; } $arr = array(70,30,40,10,80,20,90,100,75,60,45); var_dump(insertSort($arr));
结果:
array (size=11) 0 => 10 1 => 20 2 => 30 3 => 40 4 => 45 5 => 60 6 => 70 7 => 75 8 => 80 9 => 90 10 => 100 (size=11) 0 => 10 1 => 20 2 => 30 3 => 40 4 => 45 5 => 60 6 => 70 7 => 75 8 => 80 9 => 90 10 => 100