Binary search algorithm is one of the more frequent algorithms used in ordered arrays, in the non-contact binary lookup algorithm, the most common approach is to traverse the array, compare each element, and its time is O (n). But the binary lookup algorithm is better because it has a lookup time of O (LGN), such as the array {1, 2, 3, 4, 5, 6, 7, 8, 9}, find element 6, executed with binary lookup algorithm, in the order of:
1. The first step is to find the intermediate element, that is, 5, because 5<6, 6 is necessarily in the array element after 5, then it is found in {6, 7, 8, 9},
2. Looking for the median of {6, 7, 8, 9}, which is 7,7>6, 6 should be in the array element to the left of 7, then only 6 is found.
The binary search algorithm is to continuously divide the array into half, and compare the intermediate elements with goal each time.
1#include <iostream>2 using namespacestd;3 4 //Two-point search5 intBinary_search (intAintLenintgoal);6 7 intMain ()8 {9 Const intLEN =10000;Ten intA[len]; One for(inti =0; i < LEN; i++) AA[i] = i- the; - intGoal =0; - intindex =Binary_search (A, LEN, goal); the - if(Index! =-1) -cout<<goal<<"The subscript in the array is"<<binary_search (A, LEN, goal) <<Endl; - Else +cout<<"does not exist"<<goal<<Endl; - return 0; + } A at intBinary_search (intAintLenintgoal) - { - intLow =0; - intHigh = Len-1; - while(Low <=High ) - { in intMiddle = (low + high)/2; - if(A[middle] = =goal) to returnMiddle; + //on the left half - Else if(A[middle] >goal) theHigh = middle-1; * //on the right half $ ElsePanax NotoginsengLow = middle +1; - } the //didn't find + return-1; A}
This article transferred from: http://www.cnblogs.com/shuaiwhu/archive/2011/04/15/2065062.html
Binary search algorithm