二分查找递归的算法
程序员文章站
2024-03-17 23:18:58
...
特别注意的是二分查找也叫做折半查找,所以要求初始化的数组序列必须是有序的,不然会查找失败!
#include <stdio.h>
int TwoPointsSearch(int Array[],int low,int high,int key/*要找的值*/)
{
if (low<=high)
{
int mid = (low+high)>>1;
if(key == Array[mid])
{
return mid;
}
else if(key<Array[mid])
{
return TwoPointsSearch(Array,low,mid-1,key);
}
else if(key>Array[mid])
{
return TwoPointsSearch(Array,mid+1,high,key);
}
}
else
{
return -1;
}
}
int main()
{
int bArray[] = {1,9,10,13,19,25,39,39,45,49,78};
printf("%d ", TwoPointsSearch(bArray, 0, sizeof(bArray)/sizeof(bArray[0]), 39)+1);
return 0;
}