Binary search algorithm is a more frequent algorithm used in an ordered array, the most common way to do this is to traverse the array, compare each element, and the time is O (n). But the binary lookup algorithm is better because it has a lookup time of O (log n)
Sample Input
4//要查找的数6//数组长度1 4 5 7 9 12
Sample Output
1//返回下标值
1 #include <cmath>2 #include <cstdio>3 #include <vector>4 #include <iostream>5 #include <algorithm>6UsingNamespaceStd78int Binary_search (vector<Int> A,int Len,IntGoal) {9int low =0;10int high = Len-1;11while (Low <=High) {12int mid = (high-low)/2 + low;//Direct use (high + low)/2 may cause overflow13if (Goal = =A[mid])14ReturnMid15//On the left half16Elseif (Goal <A[mid])-High = mid-1;18//On the right half19ElseLow = mid +1;21st}22//Didn't find23Return-1;24}2526IntMain () {27IntV, N;Cin >> v >>Nvector<Int>AR (n);30Forint i =0; I < n; i++){>> CINAr[i];32}33int index = Binary_search (AR, n, v); 34 35 if (Index! =-1< Span style= "color: #000000;" >) 36 cout << index << Endl;37 else38 cout << " no " << v < <endl; return 0;40 41}
Binary Lookup algorithm