插入排序 直接插入排序的PHP实现 Straight Insertion Sort

直接插入排序(straight insertion sort)的PHP实现,很有用的一个函数array_splice,用好了很强的函数。

view source
print ?
01 function out_arr($arr) {
02     return implode(', '$arr).'
03 ';
04 }
05  
06 function sort_straight_insertion($arr) {
07     $ret[] = $arr[0];
08     for ($i = 1; $i count($arr); $i++ ) {
09         for($j = 0; $j count($ret); $j++ ) {
10             if$arr[$i] < $ret[$j] ) {
11                 array_splice($ret$j, 0, array($arr[$i]));
12                 break;
13             }
14         }
15         ifcount($ret) == $i ) {
16             $ret[] = $arr[$i];
17         }
18         echo sprintf('%3d'$i).' : '.out_arr($ret);
19     }
20 }
21  
22 echo '<pre>';
23 $arr = range(1, 20);
24 shuffle($arr);
25 echo 'ORG : '.out_arr($arr);
26 sort_straight_insertion($arr);
27 echo '</pre>';

你可能感兴趣的:(插入排序 直接插入排序的PHP实现 Straight Insertion Sort)