Q:

Array.binarysearch in java

Given:
import java.util.*;
public class Quest 
{ 
  public static void main(String[] args) { 
  String[] colors = {"blue", "red", "green", "yellow", "orange"}; 
  Arrays.sort(colors); 
   int s2 = Arrays.binarySearch(colors, "orange"); 
   int s3 = Arrays.binarySearch(colors, "violet"); 
    System.out.println(s2 + " " + s3);
}
}

The output is 2 -5. Why?

A:

2 is the index of orange in the sorted array (so it is the third element).
-5 is -insertion_point - 1.  The insertion point is where the key could be inserted and the array remain sorted.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#binarySearch(int[], int)

A:

The (new) sorted array looks like that:
 0       1        2         3      4
"blue", "green", "orange", "red", "yellow"

the first result 2 is the index of element "orange"
the second result is .. strange, should be negative. Please verify your results. the result of the equation (-4 - 1) = -5 The insertion point for "violet" would be at index 4 (behind "red")

Further Reading

Arrays.binarySearch - javaDoc

