Binary search, also known as binary lookup algorithm, binary search, is a search algorithm for finding a particular element in an ordered array. The search process begins with the middle element of the array, and if the intermediate element is exactly the element to be found, the search process ends, and if a particular element is greater than or less than the middle element, it is found in the half of the array greater than or less than the middle element, and is compared with the beginning of the intermediate element. If an array of steps is empty, the representation cannot be found. Each comparison of this search algorithm reduces the search scope by half.
1#include <iostream>2 using namespacestd;3 4 intBinarySearch (intKeyintLowintHighConst intarray[])5 { 6 while(Low <=High )7 {8 intMid = low+ (high-low)/2;//should in while9 if(Key >Array[mid])TenLow = mid +1; One Else if(Key <Array[mid]) AHigh = mid-1; - Else - returnmid; the } - return-1;//didn ' t find - } - + /*Recursive version - int BinarySearch (int key, int low, int high,const int arr[]) + { A int mid = low + (high-low)/2;//does not use (Low+high)/2 which might encounter overflow issue at if (Low>high) - return-1; - Else - { - if (arr[mid] = = key) - return mid; in else if (arr[mid]>key) - return BinarySearch (Key, Low, mid-1, arr); to Else + return BinarySearch (Key, Mid + 1, high, arr); - } the } * */ $ Panax Notoginseng voidResultinta) - { the if(A = =-1) +cout <<"BinarySearch failed, not included"<<Endl; A Else thecout <<"BinarySearch result is an array number"<< a <<Endl; + } - intMain () $ { $ intarray[Ten] = {1,3,5,8, One, +, -, $, $, About }; - intA = BinarySearch (5,0,9, array); - intb = BinarySearch (4,0,9, array); the result (a); - result (b);Wuyi //System ("pause"); the return 0; -}
Note In a non-recursive version, int mid = low + (high-low)/2; Should be inside the loop.
Binary search algorithm