本人比较喜欢递归,但这里有两种做法
//============非递归做法========================//
#include <iostream>
using namespace std;int a[11];
int BinSearch(int s[], int size, int key)
{
int low=0, high = size - 1, mid;
while(low <= high)
{
mid=(low + high)/2;
if(s[mid] == key)
return mid;
if(s[mid] > key)
high=mid-1;
else
low=mid+1;
}
return -1;
}
int main()
{
printf("请输入十个整数:\n");
for(int i=1; i<11; ++i)
scanf("%d",&a[i]);
printf("%d", BinSearch(a, 11, 10));
return 0;
}
//==========================递归==================//
- int BinSearch(int Array[],int low,int high,int key)
- {
- if (low<=high)
- {
- int mid = (low+high)/2;
- if(key == Array[mid])
- return mid;
- else if(key<Array[mid])
- return BinSearch(Array,low,mid-1,key);
- else if(key>Array[mid])
- return BinSearch(Array,mid+1,high,key);
- }
- else
- return -1;
- }