i=3 21|254 9 6[08)25 2345 = 212525 目o同 12345 temp i=5 16212525 49 0123 5 tem
25* 0 1 2 3 4 5 0 1 2 3 4 5 temp 16 0 1 2 3 4 5 temp 08
49 完成[o8 1621252 012345 i=4时的排序过程 = j=32112525 49 08 16 012345 ep = 6 j=22112525 49 08 16 012345 emp
16 49 0 1 2 3 4 5 0 1 2 3 4 5 temp 0 1 2 3 4 5 temp 完成
2125 16 25 49 16 2345 i=4 j=021 2525 49 0 2345 tem i=4 16 212525 49 08 16 012345temp
25 25* 0 1 2 3 4 5 0 1 2 3 4 5 temp 0 1 2 3 4 5 temp 21
直接插入排序的算法 template <class Type> void Insertion Sort datalist<Type> list )i ∥按关键码Key非递减顺序对表进行排序 for int i=l; i< list. CurrentSize; i++) Insert( list, i ) template <class Type> viod Insert( datalist<Type>& list, int i)t Element<Type> temp= list. Vector]: int =i; ∥后向前顺序比较
template <class Type> void InsertionSort ( datalist<Type> & list ) { //按关键码 Key 非递减顺序对表进行排序 for ( int i = 1; i < list.CurrentSize; i++ ) Insert ( list, i ); } template <class Type> viod Insert ( datalist<Type> & list, int i ) { Element<Type> temp = list.Vector[i]; int j = i; //从后向前顺序比较
while(>0 &i& temp. getKey (< list. Vector/-1getKey o) f list. Vector]- list. Vector/-1];j-3 list. Vector]=temp 算法分析 若设待排序的对象个数为 curremtsize=n,则 该算法的主程序执行n-1趟。 关键码比较次数和对象移动次数与对象关键码 的初始排列有关
while ( j > 0 && temp.getKey ( ) < list.Vector[j-1].getKey ( ) ) { list.Vector[j] = list.Vector[j-1]; j--; } list.Vector[j] = temp; }