本文针对折半插入排序。
这种排序方法是对直接插入排序的改进,即查找操作采用折半减少比较操作次数,但是数据移动次数不变,因此时间复杂度仍是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;
//折半插入排序
void binary_insertion_sort(list *l)
{
int i,j,m,low,high;
for(i = 2;i <= l->length;++i){
l->array[0] = l->array[i];
low = 1;
high = i - 1;
while(low <= high){
m = (low + high) / 2;
if(l->array[0].key < l->array[m].key)
high = m - 1;
else
low = m + 1;
}
for(j = i - 1;j >= high + 1;--j)
l->array[j + 1] = l->array[j];
l->array[high + 1] = l->array[0];
}
}
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);
binary_insertion_sort(&l);
printf("after binary insertion sort:\n");
print_array(&l);
}
结果:
[20:29:49]# ./c
befor sort:
5 6 13 5 22 2 2 4 6 5 99 7 6 15 1 22 15 12 58 12
after binary insertion sort:
1 22 2 4 5 6 6 5 6 15 13 5 15 12 22 2 58 12 99 7