// 原数据有序
int binarySearch(vector<int>& a, int rightIndex, int leftIndex, int target)
{
if (rightIndex > leftIndex) return -1;
int midIndex = (leftIndex + rightIndex) / 2;
if (a[midIndex] == target) return midIndex;
if (target < a[midIndex]) return binarySearch(a, rightIndex, midIndex - 1, target);
if (target > a[midIndex]) return binarySearch(a, midIndex + 1, leftIndex, target);
}
int main()
{
vector<int> a{ 1,2,3,4,5,6,7,8,9 };
int target;
while (1) {
cin >> target;
int i = binarySearch(a, 0, a.size() - 1, target);
cout << i << endl;
}
return 0;
}
二分查找
最新推荐文章于 2024-09-03 18:29:17 发布