CodeLibrary/09_Clion_Cplus_work_20240620/function_01.cpp
2024-06-22 23:31:01 +08:00

28 lines
741 B
C++

#include <iostream>
using namespace std;
int binarySearchDesc(int arr[], int n, int k) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == k)
return mid;
if (arr[mid] < k) // 由于是降序,此处应为小于
high = mid - 1;
else
low = mid + 1;
}
return -1; // 查找失败
}
//int main() {
// int arr[] = {98, 86, 75, 64, 55, 48, 37, 22, 13};
// int n = sizeof(arr)/sizeof(arr[0]);
// int k = 22;
// int result = binarySearchDesc(arr, n, k);
// if(result != -1)
// cout << "Element found at index: " << result;
// else
// cout << "Element not found";
// return 0;
//}