数据结构与算法-查找

查找

Posted by Zexin Zhang on October 31, 2017

作业-二分查找

  • 递归二分
  • 非递归二分

测试截图

上界 下界 error AC

源码

#include <cstdio>

#include <cmath>

#include <cstring>

using namespace std;

int RecursivelyBinarySearch(int a[],int low,int high,int x){
	while(low<=high){
		int mid=(high+low)/2;
		if(x==a[mid]){
			return mid;break;
		}
		else if(x<a[mid])
			high=mid-1;
		else if(x>a[mid])
			low=mid+1;
	
	}

}
int NonRecursivelyBinarySearch(int a[],int low,int high,int x){
	while(low<=high){
		int mid=(low+high)/2;
		if(x==a[mid]){
			return mid;
			break;
		}
		else if(x<a[mid])
			return NonRecursivelyBinarySearch(a,low,mid-1,x);
		else if(x>a[mid])
			return NonRecursivelyBinarySearch(a,mid+1,high,x);
		
	}

}
int main(){
	int a[11]={0,3,4,23,34,78,257,789,990,1020,1023};
	int x;
	int ans1=0,ans2=0;
	printf("现有的数据为:\n");
	for(int i=1;i<=10;i++){
		printf("%d ",a[i]);
	}
	printf("\n输入你要查找的数据:\n");
	scanf("%d",&x);
	printf("(0代表查找失败!)\n"); 
	ans1=RecursivelyBinarySearch(a,1,10,x);
	printf("递归查找结果: %d\n",ans1);
	ans2=NonRecursivelyBinarySearch(a,1,10,x);
	printf("非递归查找结果:%d\n",ans2);
}