The function addToSortedI wrote is not provided by default in Java, but is still very simple. The function Collections.binarySearchreturns either a value >= 0if an element is found, or a value < 0if a value is not found. In the latter case, it returns the position of the insert (encoded to some extent so that it is always negative).
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinSort {
private static void addToSorted(List<String> list, String element) {
int index = Collections.binarySearch(list, element);
if (index < 0)
list.add(-(index + 1), element);
}
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
words.add("apple");
words.add("cat");
words.add("tree");
addToSorted(words, "banana");
System.out.println(words);
}
}
source
share