简易折半查找
作者:
3include
,
2024-09-06 15:16:21
,
所有人可见
,
阅读 1
#include <iostream>
using namespace std;
const int N = 30;
int n, nums[N];
int length;
int binary_search(int nums[],int length, int key) {
int low = 0, high = length - 1, mid;
while(low <= high) {
mid = (low + high) / 2;
if(nums[mid] == key)
return mid + 1;
if(mid < key)
low = mid + 1;
if(mid > key)
high = mid - 1;
}
return -1;
}
int main() {
cin >> n;
for (int i = 0; i < n; i ++) {
cin >> nums[i];
}
int res = binary_search(nums, n, 20);
if(res != -1)
printf("它在数组中的第%d个位置!", res);
else
printf("对不起,没有此元素!");
return 0;
}