Basic Knowledge (03)--Two points inquiry

Source: Internet
Author: User

The dichotomy method is suitable when the amount of data is large, but the precondition of using dichotomy is that the data is not duplicated in order .
Binary search, also known as binary query, as the name implies is from the middle of the comparison to find, the basic idea is: the assumption of data in ascending order, for the given value X, from the middle of the sequence of the comparison, if the current position value equals X, the query succeeds, if X is less than the current position value, Look in the first half of the sequence, and if X is greater than the current position value, continue searching in the second half of the sequence until it is found.

Under the Java.util package has a arrays class, which provides a two-point method of query, you can go to see how the specific source code is implemented:
View the BinarySearch (int[] a,int key) method in Java.util.Arrays:

The source code is as follows:

1 // Use the binary search method to search for the specified array of int, which has obtained the subscript of the specified key value in the array 2   Public Static int binarysearch (intint  key) {3       // Call internal method  4         return binarySearch0 (A, 0, a.length, key); 5  }
1  //JDK-provided binary search source code2  Private Static intBinarySearch0 (int[] A,intFromIndex,intToindex,intkey) {3         intlow = FromIndex;//Low Pointer4         intHigh = toIndex-1;//High Pointer5        //exits while loop when the value of the low pointer is greater than the value of the high pointer6          while(Low <=High ) {7             intMid = (low + high) >>> 1;//take the middle value8             intMidval =A[mid];9 Ten             if(Midval <key) OneLow = mid + 1; A             Else if(Midval >key) -High = Mid-1; -             Else the                 returnMid//Key found -         } -         return-(low + 1);//key not found. -}

Basic Knowledge (03)--Two points inquiry

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.