Algorithm ---- binary search algorithm, algorithm ---- binary
Binary Search is a frequently used algorithm in Ordered arrays. When you are not in contact with the binary search algorithm, the most common method is to traverse the array, compare with each element. The time is O (n ). but the binary search algorithm is better, because the search time is O (lgn), such as the Array {1, 2, 3, 4, 5, 6, 7, 8, 9 }, search element 6. If the binary search algorithm is used for execution, the order is as follows:
1. the first step is to find the intermediate element, that is, 5. Because 5 <6, 6 must be included in the array element after 5, so it is searched in {6, 7, 8, 9,
2. Search for the median of {6, 7, 8, 9}, which is 7> 6. Then 6 should be in the array element on the left of 7, and only 6 is left.
The binary search algorithm is to continuously split the array into half, and compare the intermediate elements with the target to be searched each time.
#include <iostream>#include <vector>using namespace std;int binary_search(vector<int> &vec, int value){size_t len = vec.size();int start = 0;int end = len-1;while (start <= end){int mid = (end + start) / 2;if (vec[mid] == value)return mid;else if (vec[mid] > value)end = mid - 1;elsestart = mid + 1;}return -1;}int main(int argc, char*argv[]){int idx = 0;vector<int> vec = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };idx=binary_search(vec, 6);cout << idx << endl;return 0;}
Php code:
function binsearch($x,$a){$c=count($a);$lower=0;$high=$c-1;while($lower<=$high){$middle=intval(($lower+$high)/2);if($a[$middle]>$x)$high=$middle-1;elseif($a[$middle]<$x)$lower=$middle+1;elsereturn $middle;}return -1;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.