有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

二进制搜索java数组。binarySearch无法找到目标

String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   

// Search for the word "cat" 
int index = Arrays.binarySearch(sortedArray, "Quality");  

我总是得到-3。问题出在"Name"。为什么我的数组中不能有"Name"?有什么想法吗


共 (3) 个答案

  1. # 1 楼答案

    必须对数组进行排序,才能进行二进制搜索。{a1}的javadoc说:

    The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined.

    (重点加上。)

    原因很简单。二进制搜索算法的前提是输入数组已排序

  2. # 2 楼答案

    要使用binarySearch,首先需要自己对数组进行排序:

    String[] sortedArray = new String[]{"Quality", "Name", "Testing", "Package"};   
    
    java.util.Arrays.sort(sortedArray);
    
    int index = Arrays.binarySearch(sortedArray, "Quality");  
    
  3. # 3 楼答案

    必须对数组进行排序。从binarySearch()的Javadoc:

    The range must be sorted into ascending order according to the natural ordering of its elements prior to making this call. If it is not sorted, the results are undefined.