直接插入排序的基本思想是:当插入第i(i>=1)个对象时,前面的V[0],V[1],…,V[i-1]已经排好序,这时,用V[i]的关键码与V[i-1],V[i-2],…的关键码顺序进行比较,找到插入位置即将V[i]插入,原来位置上的对象向后顺移。
1
template<class Type> void InsertionSort (datalist<Type> &list){
2
//按关键码Key非递减顺序对表进行排序。
3
for(int i=1;i<list.CurrentSize;i++) Insert(list,i);
4
};
5![](/Images/OutliningIndicators/None.gif)
6
template<class Type> void Insert(datalist<Type> &list,int i){
7
//将元素list.Vector[i]按其关键码插入到有序表list,Vector[0],
,list.Vector[i-1]中,
8
//使得list.Vector[0]到list.Vector[i]有序
9
Element<Type> temp = list.Vector[i];
10
int j = i;
11
while(j>0&&temp.getKey()<list.Vector[j-1].getKey()){
12
list.Vector[j] = list.Vector[j-1];
13
j--;
14
}
15
list.Vector[j] = temp;
16
}
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
2
![](/Images/OutliningIndicators/InBlock.gif)
3
![](/Images/OutliningIndicators/InBlock.gif)
4
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
5
![](/Images/OutliningIndicators/None.gif)
6
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
7
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/dot.gif)
8
![](/Images/OutliningIndicators/InBlock.gif)
9
![](/Images/OutliningIndicators/InBlock.gif)
10
![](/Images/OutliningIndicators/InBlock.gif)
11
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
12
![](/Images/OutliningIndicators/InBlock.gif)
13
![](/Images/OutliningIndicators/InBlock.gif)
14
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
15
![](/Images/OutliningIndicators/InBlock.gif)
16
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
直接插入排序源码