Java implementation binary search \ Binary Lookup

Source: Internet
Author: User

Binary search also known as binary lookup, the advantage is less than the number of comparisons, Find Fast, the disadvantage is that the unknown origin table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent.

The algorithm requires:

1, the sequential storage structure must be used.

2, must be ordered by the size of the key words.

The time complexity of the algorithm is the worst: O (Logn)

Note that there are mid, low, high

Its Java implementation code is as follows (the code is flawed, just the basic implementation, needs to be perfected):

Public class BinarySearch {

/**

     * @param args

*/

Public static void main (string[] args) {

// TODO Auto-generatedmethod stub

int [] src = {1,3,5,7,8,9};

System. out. println (binarysearch(src,3));

}

private static int binarysearch (int[] src,int i) {

int low=0;

int high=src. length-1;

System. out. println ("+low");

System. out. println ("+high");

while (Low<=high) {

int mid = (Low+high)/2;

System. out. println ("Mid is"+mid);

if (src[mid]==i) {

return mid;

}Else if(I<src[mid]) {

High=mid-1;

}Else{

low=mid+1;

}

}

return -1;

}

}

Java implementation binary search \ Binary Lookup

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.