#include <iostream>
using namespace std;
int recursionBinarySearch(int* arr, int num, int left, int right)
{
if (left <= right)
{
int middle = (left + right) / 2;
if (arr[middle] == num)
return middle;
if (arr[middle] > num)
right = middle - 1;
else
left = middle + 1;
return recursionBinarySearch(arr, num, left, right);
}
return -1;
}
int main(void)
{
int num = 0;
int arr[] = { 2, 5, 8, 13, 16, 19, 20, 33, 35, 39, 48, 51, 54, 58, 62, 64, 67, 76, 85, 98 };
int len = sizeof(arr) / sizeof(arr[0]);
cout << "请输入你要查找的数字:" << endl;
cin >> num;
int pos = recursionBinarySearch(arr, num, 0, len - 1);
if (pos == -1)
cout << "没有找到你要查找的数字" << endl;
else
cout << "你要查找的数字在" << pos + 1 << "的位置上" << endl;
system("pause");
return 0;
}
递归二分查找算法
最新推荐文章于 2024-08-14 11:57:07 发布