Java binarysearch way

Today, with the technology of tomorrow "Java from entry to the master," a book to learn Java, see an array of queries can not understand one thing here, not the same feeling on the machine and experiment in terms of the book, then Baidu, the feeling is that Scripture says, is wrong, what is now recording.


 

First class array sort need to import java.util.Arrays

There are two binarysearch usage, a search in the whole array, a search in the specified range, in fact, are similar, the former can be considered as a special case of the latter.

Usage 1

binarySearch(Object[], Object key)

Object is the target array, key target value, requires that the target array must be sorted , otherwise it can not find the right results

Inquiry is nothing more than two results, one is the target value in the target array, and the other is not

Therefore, the return value is also divided into both positive and negative, the target value in the target array and returns index (if there are multiple same can not be found to determine which, because it is a binary search)

The array is not within the target returns - (index + 1 is greater than a first target value of the element). Similarly, if the value in the array than the target value is small, the return - (array length +1)

Example:

import java.util.Arrays;
public class number {
    public static void main(String[] args) {
    int a[] = new int[] {1, 3, 4, 6, 8, 9};  
    int x1 = Arrays.binarySearch(a, 5);  
    int x2 = Arrays.binarySearch(a, 4);  
    int x3 = Arrays.binarySearch(a, 0);  
    int x4 = Arrays.binarySearch(a, 10);
    System.out.println(x1+" "+x2+" "+x3+" "+x4);
    }            
}

Output:

-4 2 -1 -7

Also can be understood:

 

Corresponds to a respective position output.

Usage 2

binarySearch(Object[], int fromIndex, int toIndex, Object key)

Added two int variables, representing the beginning and end of the interval, from fromindex (included) to toindex (not included) search inside this range, the return value is similar to the previous Usage 1, the only different is that, when the district if smaller than the target value, it is returned - (toindex + 1), if the value in the interval than the target value is large, the return - (fromindex + 1), think about not difficult to understand, the use of 1 equivalent fromindex It is 0 and the length of the array toindex usage 2.

Guess you like

Origin www.cnblogs.com/dyhaohaoxuexi/p/12234145.html