[php]数据结构算法(PHP描述) 半折插入排序 straight binary sort
生活随笔
收集整理的這篇文章主要介紹了
[php]数据结构算法(PHP描述) 半折插入排序 straight binary sort
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 <?php
2 /**
3 * 半折插入排序 straight binary sort
4 *
5 * 原理:當直接插入排序進行到某一趟時,對于 r[i] 來講,前邊 i-1 個記錄已經按關鍵字有序。此時不用直接插入排序的方法,而改為折半查找,找出 r[i] 應插的位置,然后插入。
6 */
7 function sort_binary_insertion($list)
8 {
9 $len=count($list);
10 if(empty($len)) return$list;
11
12 for($i=1; $i<$len; $i++)
13 {
14 $temp=$list[$i];
15 $low=0;
16 $high=$i-1;
17
18 while($low<=$high)
19 {
20 $mid=intval(($low+$high)/2);
21
22 //if($temp > $list[$mid]) // 從大到小
23 if($temp<$list[$mid]) // 從小到大
24 {
25 $high=$mid-1;
26 } else {
27 $low=$mid+1;
28 }
29 }
30 for($j=$i-1; $j>=$mid; $j--)
31 {
32 $list[$j+1] =$list[$j];
33 echoimplode(",",$list),"#mid=",$mid,"<br/>";
34 }
35 $list[$low] =$temp;
36 echoimplode(",",$list),"<br/>";
37 echo"--------------------------------<br/>";
38 }
39
40 return$list;
41 }
42
43
44 $list=array(4,3,2,1,5,7,3,7);
45 $list= sort_binary_insertion($list);
2 /**
3 * 半折插入排序 straight binary sort
4 *
5 * 原理:當直接插入排序進行到某一趟時,對于 r[i] 來講,前邊 i-1 個記錄已經按關鍵字有序。此時不用直接插入排序的方法,而改為折半查找,找出 r[i] 應插的位置,然后插入。
6 */
7 function sort_binary_insertion($list)
8 {
9 $len=count($list);
10 if(empty($len)) return$list;
11
12 for($i=1; $i<$len; $i++)
13 {
14 $temp=$list[$i];
15 $low=0;
16 $high=$i-1;
17
18 while($low<=$high)
19 {
20 $mid=intval(($low+$high)/2);
21
22 //if($temp > $list[$mid]) // 從大到小
23 if($temp<$list[$mid]) // 從小到大
24 {
25 $high=$mid-1;
26 } else {
27 $low=$mid+1;
28 }
29 }
30 for($j=$i-1; $j>=$mid; $j--)
31 {
32 $list[$j+1] =$list[$j];
33 echoimplode(",",$list),"#mid=",$mid,"<br/>";
34 }
35 $list[$low] =$temp;
36 echoimplode(",",$list),"<br/>";
37 echo"--------------------------------<br/>";
38 }
39
40 return$list;
41 }
42
43
44 $list=array(4,3,2,1,5,7,3,7);
45 $list= sort_binary_insertion($list);
總結
以上是生活随笔為你收集整理的[php]数据结构算法(PHP描述) 半折插入排序 straight binary sort的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: flash和html5
- 下一篇: [C#]我自己写的一个对字节中每位进行修