//二分搜素前提:参与搜素的数据必须有序
//二分搜素的时间复杂度O(log2(n))
#include<iostream>
using namespace std;
const int N = 10000010;
int n, t, a[N];
int binarysearch(int a[], int n, int target)
{
int l = 1, r = n;
while (l <= r) {
int mid = (l + r) >> 1;
if (a[mid] == target) return mid;
else if (a[mid] > target) r = mid - 1;
else l = mid + 1;
}
return -1;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
while (cin >> t) {
cout << "*" << binarysearch(a, n, t) << endl;
}
return 0;
}
二分搜索法
最新推荐文章于 2024-08-30 11:28:00 发布