Reputation: 926
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
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