插入排序

插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。 
插入排序方法分直接插入排序和折半插入排序两种。

下图演示了对4个元素(4,3,1,2)进行直接插入排序的过程,共需要(a),(b),(c)三次插入。

代码示例:

 1 <?php
 2     //插入排序
 3     include "show.php";
 4     
 5     /**
 6     * 直接插入排序
 7     */
 8     function insert_sort(&$data)
 9     {
10         $length = count($data);
11         //$length个数组元素,需要循环$length-1次
12         for($i=1; $i<$length; ++$i)
13         {
14             $key = $data[$i];
15             $j = $i - 1;
16             //通过比较找到需要插入的位置
17             while($j>=0 && $data[$j] > $key)
18             {
19                 $data[$j+1] = $data[$j];
20                 $j--;
21             }
22             $data[$j+1] = $key;
23         }
24     }
25     
26     /**
27     * 折半插入排序
28     */
29     function binary_insert_sort(&$data)
30     {
31         $length = count($data);
32         for($i=1; $i<$length; ++$i)
33         {
34             $key = $data[$i];
35             $low = 0;
36             $high = $i - 1;
37             while($low <= $high)
38             {
39                 $mid = ceil(($low+$high)/2);
40                 if($data[$mid]<$key)
41                 {
42                     $low = $mid + 1;
43                 } else {
44                     $high = $mid - 1;
45                 }
46             }
47             for($j=$i; $j>$low; --$j)
48             {
49                 $data[$j] = $data[$j-1];
50             }
51             $data[$low] = $key;
52         }
53     }
54     
55     $arr = array(8,3,9,34,1,3);
56     show($arr);//打印数组
57     insert_sort($arr);
58     //binary_insert_sort($arr);
59     show($arr);
View Code

运行结果:

原文地址:https://www.cnblogs.com/573583868wuy/p/6661811.html