![]() |
VOOZH | about |
Collections.binarySearch() is a method in Java used to search for an element in a sorted List using the binary search algorithm. It returns the index of the element if found, otherwise it returns a negative value indicating the insertion point.
Used for Natural Order:
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
Used for Custom Order:
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
-(insertion point) - 1
Example: Search an int key in a list, sorted in ascending order
3 -5
Example: Search an int key in a list, sorted in decending order
Found at index 1
Example: Search in a list of user-defined class objects
Found at index 0 -1
Note: Before using binarySearch() with a Comparator, the list must be sorted using the same Comparator; otherwise, the result is undefined.
Time Complexity
Auxiliary Space: O(1) (no extra data structures used)
| Feature | Arrays.binarySearch() | Collections.binarySearch() |
|---|---|---|
| Works on | Arrays (primitive + objects) | Collections (List types) |
| Data structures | int[], String[], etc. | ArrayList, LinkedList, etc. |
| Performance | Very efficient for arrays | Depends on List implementation |
| Requirement | Sorted array | Sorted list |