有趣的事

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

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

function out_arr($arr) {
 return implode(', ', $arr).'
';
}

function sort_straight_insertion($arr) {
 $ret[] = $arr[0];
 for ($i = 1; $i < count($arr); $i++ ) {
  for($j = 0; $j < count($ret); $j++ ) {
   if( $arr[$i] < $ret[$j] ) {
    array_splice($ret, $j, 0, array($arr[$i]));
    break;
   }
  }
  if( count($ret) == $i ) {
   $ret[] = $arr[$i];
  }
  echo sprintf('=', $i).' : '.out_arr($ret);
 }
}

echo '<pre>';
$arr = range(1, 20);
shuffle($arr);
echo 'ORG : '.out_arr($arr);
sort_straight_insertion($arr);
echo '</pre>';
```

插入 排序 直接插入 php 实现 排序 Straight Insertion Sort

相关阅读