折半查找

//2013/06/23 yong
#include<iostream>
using namespace std;
//递归算法
int CurBinSearch(int a[],int low,int high,int K)
{
   int right;
   int left;
   int mid;
   right=low;
   left=high;
   mid=right+(left-right)/2;
   if(low>=high)return -1;
   else
   {
	   if(K==a[mid])return mid;
	   else if(K<a[mid]) return CurBinSearch(a,low,mid-1,K);
	   else return CurBinSearch(a,mid+1,high,K);
   }
}
//非递归算法
int BinSearch(int a[],int low,int high,int K)
{
    int right,left,mid;
	right=low;
	left=high;
	while(right<=left)//注意事项
	{
		mid=right+(left-right)/2;
		if(K==a[mid])return mid;
		else if(K<a[mid])left=mid-1;
		else right=mid+1;
	}
	return -1;
	
}
int main()
{
	int a[]={2,3,4,5,89,90,78};
	int table1,table2;;
	int BeFound;
	cin>>BeFound;
	table1=BinSearch(a,0,6,BeFound);
	table2=CurBinSearch(a,0,6,BeFound);
    cout<<table1<<endl;
	cout<<table2<<endl;
}

你可能感兴趣的:(c,C+)