递归法实现折半查找
#include <stdio.h>
int BinSearch(int *a,int low,int high,int key)
{
int ret = -1;
int mid = 0;
ret = (a != NULL) && (low >= 0) && (high > low);
printf("Search Key: %d\n", key);
if(low <= high)
{
mid = (low + high)/2;
if(a[mid] == key)
{
return mid;
}
if(a[mid] > key)
return BinSearch(a, low, mid-1, key);
if(a[mid] < key)
{
return BinSearch(a, mid+1, high, key);
}
else
{
return -1;
}
}
}
int main()
{
int a[10] = {0,1,2,3,4,5,6,7,8,9};
int i;
int b;
b = BinSearch(a,0,9,3);
printf("key = %d\n",b);
return 0;
}