Sunday, September 26, 2010

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

No comments:

Post a Comment

Chitika