插入排序及插入排序改进

插入排序,在算法导论里面的介绍对数组 A[ ] = { 5, 2, 4,6,1,3 } 进行插入排序,排序的过程如下:

排序过程

a-->b-->c-->d-->e-->f





非降序插入排序

伪代码

for j = 2 to A.length
	key = A[j]
	// Insert A[j] into the sorted sequence A[1...j-1](这里是注释)
	i = j - 1
	while i > 0 and A[i] > key
		A[i + 1] = A[i]
		i = i - 1
	A[i + 1] = key


C语言代码

int insert_sort(int A[], int size)
{
	int i, j, key;
	if (NULL == A || size <=1 ){
		printf("File:[%s] Line:[%s] illegal array\n", __FILE__, __LINE__);
		return -1;
	}
	for(j=1; j<size; ++j){	
		key = A[j];
		// inser A[j] to the sorted sequence A[1...j-1]
		i = j - 1;
		while (i >= 0 && A[i] > key){
			A[i+1] = A[i];
			i = i - 1;
		}
		A[i+1] = key;
	}
	return 0;
}




非升序插入排序伪代码

for j = 2 to A.length
	key = A[j]
	// Insert A[j] into the sorted sequence A[1...j-1](这里是注释)
	i = j - 1
	while i > 0 and A[i] < key
		A[i + 1] = A[i]
		i = i - 1
	A[i + 1] = key

插入排序改进

二分插入排序

伪代码
for j = 2 to A.length  
    key = A[j]  
    // Insert A[j] into the sorted sequence A[1...j-1]
    i = j - 1  
    if A[i] > key  
		k = binary_search()
		for i to k
			A[i + 1] = A[i]  
			i = i - 1  
	A[i + 1] = key 
C语言代码
#define INT_AVERAGE(A,B) ((A)&(B))+(((A)^(B))>>1)

int insert_sort(int A[], int size)
{
	int i, j, key;
	int pos, k;
	if (NULL == A || size <=1 ){
		printf("File:[%s] Line:[%s] illegal array\n", __FILE__, __LINE__);
		return -1;
	}
	for(j=1; j<size; ++j){	
		key = A[j];
		i = j - 1;
		if (A[i] > key){
			pos = interative_binary_search(A, key, 0, i);
			for (; i>=pos; --i)
				A[i+1] = A[i];
		}
		A[i+1] = key;
	}
	return 0;
}

int interative_binary_search(int A[], int v, int low, int high)
{
	int mid;
	while (low < high){
		mid = INT_AVERAGE(low, high);
		if (v > A[mid])
			low = mid + 1;
		else
			high = mid - 1;
	}
	return low;
}



参考:

[1] 算法导论


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值