Binary lookup, also known as binary lookup, is based on the premise that records in a linear table must be in order (usually from large to small), and linear tables must be stored sequentially.
Algorithm thought: In the ordered table, take the intermediate record as the comparison object, if the given value is equal to the key word of the intermediate record, the search succeeds;
If the given value is less than the middle record, the left half of the intermediate record continues to be searched;
If the given value is greater than the middle record's keyword, the search continues in the right half of the middle record.
Repeat the process until the lookup succeeds, or if all lookup zones are not logged, the lookup fails.
The specific code is implemented as follows:
//with recursive implementation
int BinarySearch (int[] arr, int start, int end,int key) {
int mid = (start+end)/2;
if (key = = Arr[mid]) {
return mid;
}
if (start>=end) {
return-1;
}else if (key > Arr[mid]) {
return BinarySearch (arr, mid + 1, end, key);
} else if (Key < Arr[mid]) {
return binarysearch(arr, start, mid-1, key);
}
return-1;
}
The time complexity of binary lookups is O (LOGN).
Find algorithm-binary lookup