Java Foundation (Arrays.binarysearch) method

Source: Internet
Author: User

1. The source code can be seen,BinarySearch method calls the BinarySearch0 method, BinarySearch0 method is the standard binary search implementation.

2. For the BinarySearch0 method, pay attention to the last return statement return-(low + 1); // key not found., that is, when you do not find the key to find, the return is a negative insertion point value, the so-called insertion point value is the first element larger than key in the array index, and this index is starting from 1.

For example: There is anarray {4,6,10,21,25,95);  Return 2  2);   Returns-1 4 of the index is1 20);    Returns-4  21 of the index is4 30);   Returns-6  95 of the index is6 100); Returns 7 100 is not in the array, is larger than all elements, the insertion point value is b.length+1 7
Why use-(low+1), because if with-low words, find 2 and find 4 results are 0, so it is wrong.

3. call the BinarySearch method before calling the Arrays.sort method to sort the array, otherwise the resulting return value is variable.

     Public Static intBinarySearch (object[] A, Object key) {returnBinarySearch0 (A, 0, A.length, key); }    //Like public version, but without range checks.    Private Static intBinarySearch0 (object[] A,intFromIndex,intToindex, Object key) {        intLow =FromIndex; intHigh = ToIndex-1;  while(Low <=High ) {            intMid = (low + high) >>> 1; @SuppressWarnings ("Rawtypes") Comparable Midval=(comparable) a[mid]; @SuppressWarnings ("Unchecked")            intCMP =Midval.compareto (key); if(CMP < 0) Low= Mid + 1; Else if(CMP > 0) High= Mid-1; Else                returnMid//Key found        }        return-(low + 1);//key not found.}

Java Foundation (Arrays.binarysearch) method

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.