二分查找算法是在有序数组中用到的较为频繁的一种算法,不用二分查找算法时,最通用的一种做法是,对数组进行遍历,跟每个元素进行比较,其时间为O(n).但二分查找算法则更优,因为其查找时间为O(log n)
Sample Input
4//要查找的数
6//数组长度
1 4 5 7 9 12
Sample Output
1//返回下标值
1 //递归算法 2 int binary_search(vector<int> a, int low, int high, int goal){ 3 int mid; 4 if(low > high) 5 return -1; 6 else{ 7 mid = (high - low) / 2 + low; 8 if(a[mid] == goal) 9 return mid; 10 if(goal > a[mid]) 11 return binary_search(a, mid + 1, high, goal); 12 else 13 return binary_search(a, low, mid - 1, goal); 14 }
1 #include <cmath>
2 #include <cstdio>
3 #include <vector>
4 #include <iostream>
5 #include <algorithm>
6 using namespace std;
7 //非递归算法
8 int binary_search(vector<int> a, int len, int goal){
9 int low = 0;
10 int high = len - 1;
11 while(low <= high){
12 int mid = (high-low) /2 + low;// 直接使用(high + low) / 2 可能导致溢出
13 if(goal == a[mid])
14 return mid;
15 //在左半边
16 else if(goal < a[mid])
17 high = mid - 1;
18 //在右半边
19 else
20 low = mid + 1;
21 }
22 //没找到
23 return -1;
24 }
25
26 int main() {
27 int v, n;
28 cin >> v >> n;
29 vector<int> ar(n);
30 for(int i = 0; i < n; i++){
31 cin >> ar[i];
32 }
33 int index = binary_search(ar, n, v);
34
35 if (index != -1)
36 cout << index << endl;
37 else
38 cout << "不存在" << v <<endl;
39 return 0;
40
41 }