What is the result of the following?
public class Main{ public static void main(String[] argv){ List<String> hex = Arrays.asList("10", "8", "4B", "FF"); Collections.sort(hex); int x = Collections.binarySearch(hex, "8"); int y = Collections.binarySearch(hex, "4B"); int z = Collections.binarySearch(hex, "4F"); System.out.println(x + " " + y + " " + z); } }
D.
After sorting, hex contains [10, 4B, 8, FF].
Remember that numbers sort before letters and strings sort alphabetically.
This makes 10 come before 8.
A binary search finds 8 at index 2 and 4B at index 1.
It cannot find 4F but notices it should be at index 2.
The rule when an item isn't found is to negate that index and subtract 1. -2-1 is -3.
public class Main{ public static void main(String[] argv){ List<String> hex = Arrays.asList("10", "8", "4B", "FF"); Collections.sort(hex); /*from www . j a v a 2 s . co m*/ int x = Collections.binarySearch(hex, "8"); int y = Collections.binarySearch(hex, "4B"); int z = Collections.binarySearch(hex, "4F"); System.out.println(x + " " + y + " " + z); } }
The code above generates the following result.