Problem:

Java binary search is very fast way to find an element in a sorted collection of elements or find a place where it should be inserted. In this tutorial you will learn how to effectively use binary search in Java!

Solution:

Binary search is fundamental searching algorithm and it’s very fast. It works only with sorted collections in ascending order, so do it first if needed.

As always, Java has binary search algorithm implemented in its vast JDK API. It’s in java.util.Collections. The following example demonstrates how to use int binarySearch(List list, T key) version:

As you can see using binary search on unsorted list gives a funky result – found ‘i’ at 12, but there’s another one at index 2, which is not even close!

Another interesting thing is that Collections.binarySearch returns index of found item or (-insertionPoint – 1) when for not found item. It has to be this way, because indexes from 0 to length of string are used for found items, and only negative numbers are freely available to indicate where an element could be inserted. So we find the index by reversing the equation: -(insertionPoint +1).

Keep in mind that elements in the list have to be mutually comparable, else ClassCastException will be thrown!

In the next tutorial we’ll show how to use binarySeach(List, T, Comparator) version, which allows to compare items using own java.util.Comparator, so stay tuned! :-)