文字描述
在折半插入排序的基础上进行改进, 另设一个和待排序序列L相同的数组D, 首先将L[1]赋值给D[0], 数组D中数据是已经排好序的, first指向最小值下标,final指向最大值下标。初始时,first和final值都为0。之后将L的第二个元素开始依次和D[0]比较,大于D[0]的插入到D[0]之后的序列,小于D[0]的插入到D[0]之前的序列;这里可以将数组D想象成一个循环的圆。
示意图
算法分析
时间复杂度为n*n, 辅助空间为n,是稳定的排序方法。
二路插入排序和折半插入排序比,只是可以大概率的减少移动的次数,但不能绝对避免,当待排序序列中的第一个数据就是最小值或者最大值时,2-路插入排序将完全失去它的优越性。
代码实现
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define EQ(a, b) ((a) == (b)) 5 #define LT(a, b) ((a) < (b)) 6 #define LQ(a, b) ((a) <= (b)) 7 8 #define MAXSIZE 20 9 typedef int KeyType; 10 typedef int InfoType; 11 typedef struct{ 12 KeyType key; 13 InfoType otherinfo; 14 }RedType; 15 16 typedef struct{ 17 RedType r[MAXSIZE+1]; 18 int length; 19 }SqList; 20 21 void PrintList(SqList L){ 22 int i = 0; 23 printf("len:%d; data:", L.length); 24 for(i=1; i<=L.length; i++){ 25 printf("%d ", L.r[i].key); 26 } 27 printf("\n"); 28 return ; 29 } 30 31 #define DEBUG 32 33 void TwoInsertSort(SqList *L) 34 { 35 RedType D[MAXSIZE] = {0}; 36 D[0] = L->r[1]; 37 38 int i = 0, j = 0, n = L->length; 39 int first = 0, final = 0, m = 0; 40 int k = 0; 41 #ifdef DEBUG 42 for(j=0; j<n; j++){ 43 printf("%d ", D[j].key); 44 } 45 printf("\nthe %d lap:fist=%d, final=%d\n\n", i, first, final); 46 #endif 47 48 for(i=2; i<=L->length; i++){ 49 if(LT(L->r[i].key, D[first].key)){ 50 first = (first-1+n)%n; 51 D[first] = L->r[i]; 52 }else if(LT(D[0].key, L->r[i].key)){ 53 final = (final+1)%n; 54 D[final] = L->r[i]; 55 }else{ 56 k = (final+1)%n; 57 while(LT(L->r[i].key, D[(k-1+n)%n].key)){ 58 D[(k+n)%n] = D[(k-1+n)%n]; 59 k = (k-1+n)%n; 60 } 61 D[(k+n)%n] = L->r[i]; 62 final = (final+1)%n; 63 } 64 #ifdef DEBUG 65 for(j=0; j<n; j++){ 66 printf("%d ", D[j].key); 67 } 68 printf("\nthe %d lap:fist=%d, final=%d\n\n", i, first, final); 69 #endif 70 } 71 //copy sorted data to primay list. 72 for(j=0; j<n; j++){ 73 L->r[1+j] = D[first]; 74 first = (first+1)%n; 75 } 76 } 77 78 int main(int argc, char *argv[]) 79 { 80 if(argc < 2){ 81 return -1; 82 } 83 SqList L; 84 int i = 0; 85 for(i=1; i<argc; i++){ 86 if(i>MAXSIZE) 87 break; 88 L.r[i].key = atoi(argv[i]); 89 } 90 L.length = (i-1); 91 92 TwoInsertSort(&L); 93 PrintList(L); 94 return 0; 95 }
运行
[jennifer@localhost Data.Structure]$ ./a.out 12 5 7 4 5 3 45 76
12 0 0 0 0 0 0 0
the 0 lap:fist=0, final=0
12 0 0 0 0 0 0 5
the 2 lap:fist=7, final=0
7 12 0 0 0 0 0 5
the 3 lap:fist=7, final=1
7 12 0 0 0 0 4 5
the 4 lap:fist=6, final=1
5 7 12 0 0 0 4 5
the 5 lap:fist=6, final=2
5 7 12 0 0 3 4 5
the 6 lap:fist=5, final=2
5 7 12 45 0 3 4 5
the 7 lap:fist=5, final=3
5 7 12 45 76 3 4 5
the 8 lap:fist=5, final=4
len:8; data:3 4 5 5 7 12 45 76
[jennifer@localhost Data.Structure]$