java 用Arrays.binarySearch解读 快速定位数字范围

在一些时候,需要用给一个数字找到适合的区间,Arrays.binarySearch可达到这个目的.

static intbinarySearch(int[] a, int key) 
          Searches the specified array of ints for the specified value using the binary search algorithm.

import java.util.Arrays;
public class Test {
    public static void main(String[] args) {
        // initializing unsorted byte array
        byte byteArr[] = {10,20,15,22,35};
        // sorting array
        Arrays.sort(byteArr);
        // let us print all the elements available in list
        System.out.println("The sorted byte array is:");
        for (byte number : byteArr) {
          System.out.println("Number = " + number);
        }
        // 输入需要搜索的数字
        byte searchVa1 = 15;  //搜索在数组的数字
        byte searchVa2 = 22;  //搜索不在数组的数组
        
        int retVa1 = Arrays.binarySearch(byteArr,searchVa1);
        int retVa2 = Arrays.binarySearch(byteArr, searchVa2);
        
        int position1=retVa1>=0?retVa1:-retVa1-2;
        int position2=retVa2>=0?retVa2:-retVa2-2;
        
        System.out.println("The index of 10 element is : " + position1);  //输出结果为 1
        System.out.println("The index of 22 element is : " + position2);  //输出结果为 3
        
      }
}
15在数组排序后是第2个,索引为1
22在数组排序后在第3个和第4个中间  位置排在第4个,索引为3
需要注意的是,用Arrays.binarySearch搜索时,必须对元素进行排序.




qq3061280@163.com
原文地址:https://www.cnblogs.com/aibuli/p/b81a84d9e6f2b4fc0082d2ad12953fd6.html