Sunday, September 26, 2010

Inserting an Element into a Sorted List in java

Although binarySearch() is used to locate existent elements, it can also be used to determine the insert index for non-existent elements. Specifically, the insertion index is computed in the following way: insert-index = (-return-value)-1

// Create a list with an ordered list of items
List sortedList = new LinkedList();

sortedList.addAll(Arrays.asList(new String[]{"ant", "bat", "cat", "dog"}));

// Search for the non-existent item
int index = Collections.binarySearch(sortedList, "cow"); // -4

// Add the non-existent item to the list
if (index < 0) { sortedList.add(-index-1, "cow"); }

No comments:

Post a Comment

Chitika