天天看點

折半查找原理(C++)

#include<stdio.h>
#include<iostream>
using namespace std;

int find(int a[],int num)
{
	int low=0;
	int high=8;
	int mid=(low+high)/2;
	while(a[mid]!=num)
	{
		if(high<=low)
			return -1;
		cout<<"high="<<high<<endl;
		cout<<"low="<<low<<endl;
		cout<<"mid="<<mid<<endl;
		if(num>a[mid]) low=mid+1;
		else high=mid-1;
		mid=(high+low)/2;

	}
	/*while(high>=low)
	{
		cout<<"high="<<high<<endl;
		cout<<"low="<<low<<endl;
		cout<<"mid="<<mid<<endl;
		if(a[mid]==num)return mid;
		else if(a[mid]>num)high=mid-1;
		else low=mid+1;
		mid=(high+low)/2;
	}*/
	return mid;
}
void main()
{
	int nums[10]={1,2,3,4,5,6,7,8,9};
	int pos;
	int num;
	cin>>num;
	pos=find(nums,num);
	cout<<pos<<endl;
}