2.插入排序——折半插入排序

本文針對折半插入排序。
這種排序方法是對直接插入排序的改進,即查找操作採用折半減少比較操作次數,但是數據移動次數不變,因此時間複雜度仍是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


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章