Binary search is a common search method that requires elements in an array to be stored in an orderly manner. Without losing its generality, we assume that array elements are stored in ascending order. The binary search method first compares the keyword to the element in the middle of the array, and compares the results in three cases:
1) If the keyword is smaller than the central element, we only need to continue the search in the first half of the array.
2) If the keyword is equal to the central element, the search ends and the matching element is found.
3) If the keyword is larger than the central element, we only need to continue the search in the second half of the array.
The code for the binary search is as follows:
#include <iostream>using namespace Std;int binarysearch (int a[],int number,int len) {int Left=0,right=len-1;int Middle;while (left<=right) {middle= (left+right)/2;if (a[middle]<number) {left=middle+1;} else if (a[middle]>number) {right=middle-1;} Else{return Middle;}} return-1;} int _tmain (int argc, _tchar* argv[]) {int a[]={2,4,7,10,11,45,50,59,60,66,69,70,79};int result=binarysearch (a,45,13); if (result = =-1) {cout<< "Not find this number" <<ENDL;} else{cout<< "The index of number is" <<RESULT<<ENDL;} return 0;}
The output is:
The index of number is 5
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Algorithmic Learning Notes"-two-point lookup algorithm