簡體   English   中英

為什么這個二進制搜索返回-1,即使該元素在數組中

[英]Why does this binary search return -1 even though the element is in the array

打印出-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"));


        }
    }

二進制搜索僅適用於已排序的數組。

數組API

二進制搜索需要對數組進行排序(堆)。 您可以使用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

必須對列表進行排序以使用二進制搜索

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM