Will Jamieson
Will Jamieson

Reputation: 926

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

It prints out -1 I might be missing how that happens since "Germany" is definitely in the array

    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"));


        }
    }

Upvotes: 3

Views: 747

Answers (3)

Sam
Sam

Reputation: 7858

A binary search requires the array to be sorted (heap). You can use 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"));


    }
}

Note, that this requires the element type to either be a primitive type, or an impementation of the interface Comparable<T>, which applies for String.

Upvotes: 7

tungsten
tungsten

Reputation: 328

The list has to be sorted to use binary search

Upvotes: 1

MrSmith42
MrSmith42

Reputation: 10151

binary search only works on sorted arrays.

Arrays API

Upvotes: 10

Related Questions