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

二分,一种常用的查找方法,时间复杂度O(log2(n)),二分的思想很重要,常常可以减小算法的时间复杂度。一开始自己只是记住了怎样去写,现在研究了一下,有了些新的体会。二分函数的写法并不是只有固定的那一套:low=0; high=n; if(a[mid]>val)high=mid-1; else if(a[mid]

输入文件内容:

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 
#include
#include
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&&lowdepth)break;  //查找次数不超过判定树的深度
		mid=(high+low)/2;
		count++;
		if(a[mid]==x)return mid;
		else if(a[mid]>n){
		int i;
		for(i=1;i<=n;i++)cin>>a[i];
		for(i=1;i<=n+3;i++){
			cin>>x;
			cout<
输出:

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

第二种:

#include 
#include
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]>n){
		int i;
		for(i=1;i<=n;i++)cin>>a[i];
		for(i=1;i<=n+3;i++){
			cin>>x;
			cout<
输出:

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



你可能感兴趣的:(algorithm_查找)