折半插入排序的基本思想是:设在顺序表中有一个对象序列V[0],V[1],…,V[n-1]。其中,V[0],V[1],…,V[i-1]是已经排好序的对象。在插入V[i]时,利用折半查找法寻找V[i]的插入位置。
折半插入排序源码
1
template<class Type>
2
void BinaryInsertSort(datalist<Type> &list){
3
for(int i=1;i<list.CurrentSize;i++) BinaryInsert(list,i);
4
};
5![](/Images/OutliningIndicators/None.gif)
6
template<class Type>
7
void BinaryInsert(datalist<Type> &list){
8
//利用折半查找,按list.Vector[i].key在list.Vector[0]到list.Vector[i-1]中
9
//查找list.Vector[i]应插入的位置,再空出这个位置进行插入。
10
int left=0,right=i-1;
11
Element<Type> temp = list.Vector[i];
12
while(left<=right){//利用折半查找插入位置
13
int middle = (left+right)/2;//取中点
14
if(temp.getKey()<list.Vector[middle].getKey())//插入值小于中点值
15
right = middle - 1;//向左缩小区间
16
else left = middle + 1;//否则,向右缩小区间
17
}
18![](/Images/OutliningIndicators/InBlock.gif)
19
for(int k=i-1;k>=left;k--) list.Vector[k+1]=list.Vector[k];//成块移动空出插入位置
20
list.Vector[left]=temp;//插入
21
};
![](/Images/OutliningIndicators/None.gif)
2
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](/Images/OutliningIndicators/InBlock.gif)
4
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
5
![](/Images/OutliningIndicators/None.gif)
6
![](/Images/OutliningIndicators/None.gif)
7
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
8
![](/Images/OutliningIndicators/InBlock.gif)
9
![](/Images/OutliningIndicators/InBlock.gif)
10
![](/Images/OutliningIndicators/InBlock.gif)
11
![](/Images/OutliningIndicators/InBlock.gif)
12
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
13
![](/Images/OutliningIndicators/InBlock.gif)
14
![](/Images/OutliningIndicators/InBlock.gif)
15
![](/Images/OutliningIndicators/InBlock.gif)
16
![](/Images/OutliningIndicators/InBlock.gif)
17
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
18
![](/Images/OutliningIndicators/InBlock.gif)
19
![](/Images/OutliningIndicators/InBlock.gif)
20
![](/Images/OutliningIndicators/InBlock.gif)
21
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
折半插入排序源码