王道考研C语言数据结构:排序

/**
 * 插入排序
**/
#include<stdio.h>
// 对数组A进行插入排序 (升序)
void insertSort(int A[],int n){
	int temp;
	// 从第二个元素开始执行(n-1)次
	for(int i=1;i<n;i++){
		// A[i] < A[i-1]   临时存起来 temp = A[i]
		if(A[i] < A[i-1]){
			temp = A[i];
			// 逆序遍历j=i-1,temp > A[j],j--  每次向后移动1位
			for(int j=i-1;j>=0 && temp<A[j];j--){
				// 每次向后移动1位
				A[j+1] = A[j];
			}
			//最后得到j的位置插入 A[j] = temp
			A[j+1] = temp;
		}
	}
}
// 折半插入排序
void insertSortHalf(int A[],int n){
	int temp;
	int low,hight,mid;
	// 从第二个元素开始执行(n-1)次
	for(int i=1;i<n;i++){
		// A[i] < A[i-1]   临时存起来 temp = A[i]
		if(A[i] < A[i-1]){
			temp = A[i];
			low = 0;
			hight = i-1;
			// 二分查找位置
			while(low <= hight){
				mid = (low+hight)/2;
				if(A[mid] > A[i]){
					hight = mid-1;
				}else{
				    low = mid+1;
				}
			}
			// 找到位置low 大的向后移动
			for(int j=i-1;j>=hight+1;--j){
				A[j+1]=A[j];
			}

			A[hight+1] = temp;
		}
	}
}
/**
 * 希尔排序
**/
void shellSort(int A[],int n){
	int temp ;
	// 求步长d(执行n/2次)
	for(int d = n/2 ;d>=1;d=d/2){
		// 进行插入排序
		for(int i=d+1;i<n;i++){
			// 小于前子列表最大值才插入
			if(A[i] < A[i-d]){
				temp = A[i];
				// 对前子列表进行插入排序
				for(int j=i-d;j>0&&A[j]>temp;j--){
					// 向后移动
					A[j+d]=A[j];
				}
				A[j+d] = temp;
			}
		}
	}
}



void main(){
	int A[5] = {1,5,2};
	shellSort(A,3);
	for(int i=0;i<3;i++){
		printf("%d\t", A[i]);
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值