折半查找(二分的两种写法)

二分,一种常用的查找方法,时间复杂度O(log2(n)),二分的思想很重要,常常可以减小算法的时间复杂度。一开始自己只是记住了怎样去写,现在研究了一下,有了些新的体会。二分函数的写法并不是只有固定的那一套:low=0; high=n; if(a[mid]>val)high=mid-1; else if(a[mid]<val) low=mid+1; else return mid; 设置界的角度不同,跳出循环的条件就不同,low, high”指针“的变化也略有不同。

输入文件内容:

8  
4 11 14 18 41 44 51 72
4 11 14 18 41 44 51 72 36 2 100
9
4 11 14 18 41 44 51 72 89
4 11 14 18 41 44 51 72 89 36 2 100

第一种:

#include <iostream>
#include<cstdio>
#include<cmath>
using namespace std; 
const int maxn=1000;
int n,x,a[maxn];
int midfind(){
	int low=0,high=n+1,mid,count=0,depth=int(log2(n))+1;  
	while(high>1&&low<n){
		if(count>depth)break;  //查找次数不超过判定树的深度
		mid=(high+low)/2;
		count++;
		if(a[mid]==x)return mid;
		else if(a[mid]<x)low=mid;
		else high=mid;
	}
	return 0;
}
int main(int argc, char *argv[]) {
	freopen("cin.txt","r",stdin);
	while(cin>>n){
		int i;
		for(i=1;i<=n;i++)cin>>a[i];
		for(i=1;i<=n+3;i++){
			cin>>x;
			cout<<midfind()<<" ";
		}
		cout<<endl;
	}
	return 0;
}
输出:

1 2 3 4 5 6 7 8 0 0 0
1 2 3 4 5 6 7 8 9 0 0 0

第二种:

#include <iostream>
#include<cstdio>
using namespace std; 
const int maxn=1000;
int n,x,a[maxn];
int midfind(){
	int low=1,high=n,mid;
	while(low<=high){  //当不能找到目标值时就会发生low>high的情况
		mid=(high+low)/2;
		if(a[mid]==x)return mid;
		else if(a[mid]<x)low=mid+1;  //跳出循环的基础
		else high=mid-1;
	}
	return 0;
}
int main(int argc, char *argv[]) {
	freopen("cin.txt","r",stdin);
	while(cin>>n){
		int i;
		for(i=1;i<=n;i++)cin>>a[i];
		for(i=1;i<=n+3;i++){
			cin>>x;
			cout<<midfind()<<" ";
		}
		cout<<endl;
	}
	return 0;
}
输出:

1 2 3 4 5 6 7 8 0 0 0
1 2 3 4 5 6 7 8 9 0 0 0



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值