折半插入排序C语言实现

 折半插入排序的原理如上图

代码如下:

#include<stdio.h>//折半插入排序 

void zhebaninsertsort(int a[],int n){
	int i,p;
	int temp;
	for(p=1;p<n;p++){
		temp=a[p];
	    int low=0;
	     int high=p-1;
	     int mid;
	     
	     while(low<=high)
	     {
		   mid=(low+high)/2;
		   if(a[mid]<=temp)
		   low=mid+1;
		   else
		   high=mid-1;
	     }
	     
	     for(i=p-1;i>=high+1;i--) {
	     a[i+1]=a[i];
		 }
	     a[high+1]=temp;
	     
	 }
}
 
int main(){
	int n;
	scanf("%d",&n);
	int a[n];
	int i;
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	
	zhebaninsertsort(a,n);
	for(i=0;i<n;i++)
	printf("%d ",a[i]);
	return 0;
} 

在写这个代码的过程中,由于我的粗心,把while循环里面的high=mid-1写成了high=low-1

错误代码如下:

#include<stdio.h>//折半插入排序 

void zhebaninsertsort(int a[],int n){
	int i,p;
	int temp;
	for(p=1;p<n;p++){
		temp=a[p];
	    int low=0;
	     int high=p-1;
	     int mid;
	     
	     while(low<=high)
	     {
		   mid=(low+high)/2;
		   if(a[mid]<=temp)
		   low=mid+1;
		   else
		   high=low-1;
	     }
	     
	     for(i=p-1;i>=high+1;i--) {
	     a[i+1]=a[i];
		 }
	     a[high+1]=temp;
	     
	 }
}
 
int main(){
	int n;
	scanf("%d",&n);
	int a[n];
	int i;
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	
	zhebaninsertsort(a,n);
	for(i=0;i<n;i++)
	printf("%d ",a[i]);
	return 0;
} 

测试结果时:

用这个错误代码测试了好几个数据都对了,可能是阴差阳错的对的,这个却错了还把我搞懵逼了

我又补充了输出每一步的排序结果来检查我的代码到底是哪一步错了

代码如下:

#include<stdio.h>//折半插入排序 

void zhebaninsertsort(int a[],int n){
	int i,p;
	int temp;
	for(p=1;p<n;p++){
		temp=a[p];
	    int low=0;
	     int high=p-1;
	     int mid;
	     
	     while(low<=high)
	     {
		   mid=(low+high)/2;
		   if(a[mid]<=temp)
		   low=mid+1;
		   else
		   high=low-1;
	     }
	     
	     for(i=p-1;i>=high+1;i--) {
	     a[i+1]=a[i];
		 }
	     a[high+1]=temp;
	     for(i=0;i<n;i++)
	     {
	     	printf("%d ",a[i]);
	     	
		 }
		 printf("\n");
	 }
}
 
int main(){
	int n;
	scanf("%d",&n);
	int a[n];
	int i;
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	
	zhebaninsertsort(a,n);
	for(i=0;i<n;i++)
	printf("%d ",a[i]);
	return 0;
} 

 

 我又定位到错误的那一步,一步步去推导还是感觉没问题,后来看了半天才发现是mid敲成了low,但我的思想里我依然写的是mid。所以,写代码一定一定要细心再细心,一个单词的错误就可以导致很多的错误,然后我还根本发现不了。

  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值