本文針對2路插入排序。
這種排序方法是對摺半插入排序的改進,減少了數據移動操作的次數,但是需要另外申請比要排記錄所佔空間少一個記錄的內存空間,從原數組中取值按大小順序插入這個內存空間。
數據移動操作次數之所以減少是因爲如果array數組中最大值和最小值出現的比較晚,那麼一些稍微大或者小的值就可以直接往temp數組最上或者最下的地方插,就減少了數據移動次數;但是如果很早出現,就要移動和折半插入差不多的數據量了。
它的時間複雜度仍是O(n的平方)。
程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 50
typedef struct{
int key;
int other;
}node;
typedef struct
{
node array[MAXSIZE + 1];
int length;
}list;
//2路插入排序
void twoway_insertion_sort(list *l)
{
int i,j,first,final;
node *temp;
temp = (node*)malloc(l->length * sizeof(node)); //存放已經排好的數據
temp[0] = l->array[1];
first = final = 0; //first減的地方數據是小的,final加的地方數據是大的
for(i = 2;i <= l->length;++i){ //依次將l中第2個開始的數據插入到d數組
if(l->array[i].key < temp[first].key){
first = (first - 1 + l->length) % l->length;
temp[first] = l->array[i];
}
else if(l->array[i].key > temp[final].key){ /* 待插記錄大於d中最大值,插到d[final]之後(不需移動d數組的元素) */
final = final + 1;
temp[final] = l->array[i];
}
else{ /* 待插記錄大於d中最小值,小於d中最大值,插到d的中間(需要移動d數組的元素) */
j = final++; /* 移動d的尾部元素以便按序插入記錄 */
while(l->array[i].key < temp[j].key){
temp[(j + 1) % l->length] = temp[j];
j = (j - 1 + (*l).length) % l->length;
}
temp[j + 1]=l->array[i];
}
}
for(i = 1;i <= l->length;i++) //從temp中將排好的數據按順序放回l
l->array[i] = temp[(i + first - 1) % l->length];
}
void print_array(list *l)
{
int i;
for(i = 1;i <= l->length;i++)
printf("%d %d\t",l->array[i].key,l->array[i].other);
printf("\n");
}
void main()
{
node data[10]={{5,6},{13,5},{22,2},{2,4},{6,5},{99,7},{6,15},{1,22},{15,12},{58,12}};
list l;
int i;
for(i = 0;i < 10;i++)
l.array[i + 1] = data[i];
l.length = 10;
printf("befor sort:\n");
print_array(&l);
twoway_insertion_sort(&l);
printf("after twoway insertion sort:\n");
print_array(&l);
}
結果:
[21:48:18]# ./c
befor sort:
5 6 13 5 22 2 2 4 6 5 99 7 6 15 1 22 15 12 58 12
after twoway insertion sort:
1 22 2 4 5 6 6 5 6 15 13 5 15 12 22 2 58 12 99 7