The advantage of binary lookup is that the number of comparisons is small and the lookup speed is fast, but the ordered table must be established before finding. In addition, binary lookup applies only to ordered tables that are stored sequentially, not to the ordered tables of linked stores.
Suppose: Given an array p from small to large, find the position of an element on a sub-order.
The binary lookup process is to first compare the X and the middle of the array, if X is less than the value of the middle term, the first half of the linear table is searched, and if x is greater than the median, then the second half of the linear table is searched, and if x equals the value of the intermediary, the lookup ends. If this element is still not found when the sub-table length is 0, there is no x in the array.
Java code
<span style= "White-space:pre" ></span>//binary find x array, n array length, A to find the element private static int Dichotomyfind (int[ ] x, int n, int a) {int S, t, k;s = 0; Array starting element t = n-1; The last element of the array for (;;) {if (t = = s) {//Only one element if (x[t] = = a) {return t;} else {return-1;}} else {k = (s + t)/2; dichotomy if (X[k] < a) { s = k;} else if (X[k] > a) {t = k;} else {return k;}}}
Binary search for ordered arrays