Binary search for ordered arrays

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.