【问题标题】:Why does this binary search return -1 even though the element is in the array为什么即使元素在数组中,这个二分搜索也会返回 -1
【发布时间】:2013-01-03 09:54:58
【问题描述】:

它打印出 -1 我可能会错过这是如何发生的,因为“德国”肯定在数组中

    public class A 
    {
        static PrintWriter pw = new PrintWriter(System.out, true); 

        public static void main(String[] args) throws IOException 
        {
            String[] a = new String[4];
            a[0]="India";
            a[1]="Italy";
            a[2]="Germany";
            a[3]="India";

            pw.println(Arrays.binarySearch(a, "Germany"));


        }
    }

【问题讨论】:

    标签: java binary-search


    【解决方案1】:

    二分查找仅适用于已排序的数组。

    Arrays API

    【讨论】:

      【解决方案2】:

      二分查找需要对数组进行排序(堆)。你可以使用Arrays.sort()

      public class A 
      {
          static PrintWriter pw = new PrintWriter(System.out, true); 
      
          public static void main(String[] args) throws IOException 
          {
              String[] a = new String[4];
              a[0]="India";
              a[1]="Italy";
              a[2]="Germany";
              a[3]="India";
      
              Arrays.sort(a);
      
              pw.println(Arrays.binarySearch(a, "Germany"));
      
      
          }
      }
      

      注意,这要求元素类型要么是原始类型,要么是接口Comparable<T>的实现,它适用于String

      【讨论】:

        【解决方案3】:

        必须对列表进行排序才能使用二分查找

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-14
          • 1970-01-01
          • 1970-01-01
          • 2019-03-02
          • 1970-01-01
          • 2018-11-24
          • 2012-05-16
          • 1970-01-01
          相关资源
          最近更新 更多