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
This example also works if the element is a primitive type.
// 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
A negative return value indicates that the element is not in the list. However, the actual return value can be used to determine where that non-existent element should be inserted in the list if that were desired; see Inserting an Element into a Sorted Array.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.