6-1、用递归写折半查找(二分查找)
代码:
int BinarySearch_(int* List, const int N, const int Left, const int Right)
{
if (Left <= Right)
{
int Mid = (Left + Right) / 2; // mid = 中间数
if (N < List[Mid]) // 如果要找的数小于中间数, 就从中间数-1开始的右边折半
return BinarySearch_(List, N, Left, Mid - 1);
else if (N > List[Mid]) // 如果要找的数大于中间数, 就从中间数中间数+1开始的左边折半
return BinarySearch_(List, N, Mid + 1, Right);
else // 找到了就返回这个数的下标
return Mid;
}
// 如果if语句都执行完了,还没找到这个数,那就表示失败
return -1;
}
int main()
{
int Num[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 };
int Num_Maxsize = sizeof(Num) / sizeof(int);
int Num_Minsize = 1;
int a;
int Result;
cout << "请输入一个数(1-20) >";
cin >> a;
if ((Result = BinarySearch_(Num, a, 1, Num_Maxsize)) < 0)
{
cout << "未找到数字" << endl;
return -1;
}
else
{
cout << "数字 >" << a << "被找到了!它的下标是 >" << Result << endl;
}
return 0;
}