题目描述:
分析:
经典二分查找算法,实现出来很简单。
代码:
#include<iostream>
#include<string>
#include<Windows.h>
#include<cstring>
#define MAXN 10010
using namespace std;
int main()
{
int n, val;
int a[MAXN];
int st, en, mid;
cin >> n;
st = 1;en = n;
for (int i = 1;i <= n;i++) cin >> a[i];
cin >> val;
while (st <= en)
{
mid = (st + en) >> 1;
if (a[mid] == val) {
cout << mid << endl;
system("pause");
return 0;
}
else if (a[mid] > val) {
en = mid - 1;
}
else st = mid + 1;
}
cout << "-1" << endl;
system("pause");
return 0;
}