The Collections.binarySearch()
method is a part of the java.util.Collections
class, which is used to search for the position of an object in a sorted list. If the key is not found, it returns "-(insertion_point + 1)". The insertion point is the index at which the key would be inserted into the list to maintain its sorted order.
Here's an example of how to use Collections.binarySearch()
to search for an integer key in a list sorted in ascending order:
javaimport java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Example {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(10);
list.add(20);
// 10 is present at index 3.
int index = Collections.binarySearch(list, 10);
System.out.println(index); // output: 3
// 13 is not present. 13 would have been inserted
// at position 4. So the function returns -(4 + 1) = -5.
index = Collections.binarySearch(list, 13);
System.out.println(index); // output: -5
}
}
- Some important points to keep in mind when using
Collections.binarySearch()
andArrays.binarySearch()
are: - Unlike
Arrays.binarySearch()
,Collections.binarySearch()
does not take any range arguments. It simply takes the element to be searched. - The input list must be sorted for
Collections.binarySearch()
to work correctly. If the list is not sorted, the results are undefined. - If there are duplicates in the list,
Collections.binarySearch()
does not guarantee which one will be found. Arrays.binarySearch()
works for arrays, including arrays of primitive data types, whileCollections.binarySearch()
works for objects that implement theCollection
interface, such asArrayList
andLinkedList
.- The
List
or any otherCollection
must only contain non-primitive types. - The elements of the list must implement the
Comparable
interface or we must provide an object of a class that implements theComparator
interface. - If
Collections.binarySearch()
is used with anArrayList
, then the time complexity will be O(log n) for O(log n) object comparisons due to direct access. However, performing binary search on aLinkedList
will take O(n) for O(log n) object comparisons because the middle point needs to be found, which takes linear time in a linked list. - There are two
binarySearch
method declarations in theCollections
class and multiplebinarySearch
method declarations in theArrays
class.