e martë, 12 qershor 2007

Search/BinarySearch an object from a sorted list

// Create a list with an ordered list of strings
String [] str = new String("ant", "bat", "cat", "dog");
List sortedList = Arrays.asList();
Collections.sort(sortedList);

// Search for the word "cat"
int index = Collections.binarySearch(sortedList, "cat"); // 2

// Search for a non-existent element
index = Collections.binarySearch(sortedList, "cow"); // -4

Nuk ka komente: