/********************************
* 程序名称:二分查找
* 开发时间:2021-01-19
*******************************/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int s[10001]; /*数组*/
//search
int BinarySearch(int n, int s[], int x) {
int low = 0, high = n-1, middle;
while(low <= high) {
middle = (low + high) / 2;
if (s[middle]== x) {
return middle; //找到返回Middle
} else if(s[middle] > x) {
high = middle - 1; //左边
} else {
low = middle + 1; //右边
}
}
return -1; // none
}
//main() star
int main() {
//code here
int n, x;
cin >> n >> x;
for(int i =0; i<n; i++) {
cin >> s[i];
}
sort(s, s + n); //排序
for(int i =0; i<n; i++) {
cout << s[i] <<" ";
}
int exist = BinarySearch(n, s, x);
cout << exist << endl; //输出查找结果
return 0;
}
测试:
输入数据:
6 5
1 7 9 6 5 2
1 2 5 6 7 9
2
--------------------------------
Process exited after 9.959 seconds with return value 0
请按任意键继续. . .
输出数据:
2