Java:Arrays.binarySearch方法

Java If you want to find in an array value of a position, you can go to write a for loop, but obviously in Java Arrays class provides a method, then why not?

Arrays.binarySearch方法

Arrays.binarySearch(array, value);
Arrays.binarySearch(array, from_index, to_index, value);

Here array array Arrays.binarySearch methods must be sorted from small to large, and this point is important to note, because in fact this method is to use half of the algorithm. If you are not orderly array, please call Arrays.sort method to sort, binary search again.

Here to say the first line of the method, that is, to find the value in the array array index value of the last location of the first occurrence. And if there is no value in the array array value, it will return a negative number.

Besides the second method, in fact, increase the scope of a search that array [from_index] ~ array [to_index - 1] in the index to find the location of the last occurrence of value value, not found, then returns a negative number. Be sure to note here, that does not include the range of array [to_index] of.

Another point I almost forgot to say, here too early Arrays import categories, namely, to write the following code at the beginning

import java.utl.Arrays;

Code

package base;
import java.util.Arrays;

public class Arrays_binarySearch
{
    public static void main(String[] args)
    {
        int a[] = {0, 1, 1, 3, 3, 4, 4, 4, 6, 8}; // 这里a数组必须是有序的,否则无法使用binarySearch。
        System.out.println(Arrays.binarySearch(a, 4));
        System.out.println(Arrays.binarySearch(a, 5));
        System.out.println(Arrays.binarySearch(a, 2, 5 + 1, 3));
        System.out.println(Arrays.binarySearch(a, 2, 5 + 1, 8));
    }
}

Guess you like

Origin www.cnblogs.com/000zwx000/p/12461338.html