Concept
Binary search, also known as binary lookup, is a highly efficient method of finding. It has a time complexity of O (LOGN)
Two-point lookup requirements: ordered linear table
Basic ideas
The basic idea of binary search is to divide the current search interval, and the range of the interval is narrowed down one step at a time, if a direct return is found, and the reverse is stopped until the interval has only one element.
Realize
Set R as an ordered linear table with a value increment
Implementation steps:
- First determine the midpoint position of the interval: mid=[(Low+high)/2]
- Then compare the value of the key to R[mid]: if it is equal, return to the current mid directly, otherwise determine the new interval operation, which is divided into two cases
①r[mid]>key indicates that key is on the left side of the interval, so low is constant, high=mid-1
②r[mid]<key indicates that key is on the right side of the interval, so high is constant, low=mid+1
Code implementation:
public int Binsearch (int[] array, int key) { int. = 0, high = array. Length-1, mid; while (low <= high) { mid = (low + high)/2; int curvalue = Array[mid]; if (Curvalue = = key) return mid; if (Curvalue > key) {high = mid-1; } else {Low = mid + 1; } } return-1; }
Data structure and algorithm-two points lookup