#include "stdafx.h"
#include "iostream"
using namespace std;
//非递归查找
int HalfFind(int arr[],int size,int key)
{
int low=0;
int high=size-1;
int mid=0;
int result=-1;
while (low<=high)
{ mid=(low+high)/2;
if(key==arr[mid])
{
result=arr[mid];
break;
}
else if(key>mid)
low=mid+1;
else
high=mid-1;
}
return result;
}
//递归查找
int HalfFind(int arr[],int low,int high,int key)
{
if(low<=high)
{
int mid=(low+high)/2;
if(arr[mid]==key)
{
return arr[mid];
}
else if(key>arr[mid])
HalfFind(arr,mid+1,high,key);
else
HalfFind(arr,low,mid-1,key);
}
else
return -1;
}
int main(int argc, _TCHAR* argv[])
{
int test[10]={1,2,3,4,5,6,7,8,9,10};
cout<<HalfFind(test,10,1)<<endl;
cout<<HalfFind(test,0,9,1)<<endl;
getchar();
return 0;
}
[手舞足蹈]
谢谢你的发言` 非常有意义