28 lines
741 B
C++
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;
|
|
//}
|