Finding an Element in a Sorted Array
// Create an array with an ordered list of strings
String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};
// Search for the word "cat"
int index = Arrays.binarySearch(sortedArray, "cat"); // 2
// Search for a non-existent element
index = Arrays.binarySearch(sortedArray, "cow"); // -4
// Create an array with an ordered list of numbers
int[] sortedIntArray = new int[]{1, 2, 3, 5, 7};
// Search for 6
index = Arrays.binarySearch(sortedIntArray, 6); // -5
Post a comment