Determining whether or not the array contains a certain value

Use Arrays.binarySearch () method to determine

Sample code:

 public static void main(String[] args) {
        int[] array = {1, 3, 4, 2, 5, 6, 0};
        System.out.println("排序前:" + Arrays.toString(array));
        Arrays.sort(array);
        System.out.println("排序后:" + Arrays.toString(array));
        System.out.println(Arrays.binarySearch(array, 0));
    }

The results are as follows:
Here Insert Picture Description
Back to search for the index value 0, indicating that the value 0 is present in the array.

Why here to be sorted and then call Arrays.binarySearch () method it

Take a look at the sample code is not the sort:

 public static void main(String[] args) {
        int[] array = {1, 3, 4, 2, 5, 6, 0};
        System.out.println("排序前:" + Arrays.toString(array));
        System.out.println("排序后:" + Arrays.toString(array));
        System.out.println(Arrays.binarySearch(array, 0));
    }

Output:
Here Insert Picture Description
Here you can see, it's clear that there is an array 0, but the return is -1, not search on behalf of this value, and does not match the expected results.

Look Arrays.binarySearch () source code Analysis:

public static int binarySearch(int[] a, int key) {
        //真正调用的还是binarySearch0()方法
        return binarySearch0(a, 0, a.length, key);
    }
    
 private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                     int key) {
        //fromIndex默认传参就是0,所以low=0                     
        int low = fromIndex;
        //toIndex是数组的长度7,所以high=6
        int high = toIndex - 1;
        
        //循环判断
        while (low <= high) {
            //无符号右移1位,其实就是(low + high)/2,只是用移位运算更快 
            int mid = (low + high) >>> 1;
            //取得中间下标mid的数值
            int midVal = a[mid];
            //如果midVal值小于要搜索的key,则认为key在mid+1下标和high下标之间  
            if (midVal < key)
                //所以把low赋值成mid + 1
                low = mid + 1;
            //如果midVal值大于要搜索的key,则认为key在0下标和mid-1下标之间  
            else if (midVal > key)
                //所以把high赋值成mid - 1
                high = mid - 1;
            else
                //直到midVal等于key时,才退出循环,返回相应下标
                return mid; // key found
        }
        //如果实在是搜不到,就返回-(low + 1)
        return -(low + 1);  // key not found.
    }

From source can know Arrays.binarySearch () uses the dichotomy to search for positioning data, so you need to sort it, and once returns negative, it means no match is found.

to sum up

Here the actual shared determines whether the array contains the value of a another method, sometimes loops through judgment from comparison, it may be more efficient in the understanding of the Arrays.binarySearch () method may choose a better way.

Published 297 original articles · won praise 311 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_38106322/article/details/105238071