java.util.Collections.binarySearch() method is a java.util.Collections class method that returns position of an object in a sorted list.
// Returns index of key in sorted list sorted in // ascending order public static int binarySearch(List slist, T key) // Returns index of key in sorted list sorted in // order defined by Comparator c. public static int binarySearch(List slist, T key, Comparator c) If key is not present, the it returns "(-(insertion point) - 1)". The insertion point is defined as the point at which the key would be inserted into the list.
The method throws ClassCastException if elements of list are not comparable using the specified comparator, or the search key is not omparable with the elements.
Searching an int key in a list sorted in ascending order:
Searching an int key in a list sorted in descending order.
Found at index 1
Searching in a list of user-defined class objects:
Arrays.binarysearch() vs Collections.binarySearch()
Arrays.binarysearch() works for arrays which can be of primitive data type also. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList.
- If input list is not sorted, the results are undefined.
- If there are duplicates, there is no guarantee which one will be found.
- This method runs in log(n) time for a “random access” list like ArrayList. If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Java tricks for competitive programming (for Java 8)
- Java.util.Collections.rotate() Method in Java with Examples
- HashMap in Java
- Arrays.binarySearch() in Java with examples | Set 2 (Search in subarray)
- Arrays.binarySearch() in Java with examples | Set 1
- Collections.reverseOrder() in Java with Examples
- Swapping items of a list in Java : Collections.swap() with Example
- Collections.reverse() in Java with Examples
- Deque interface in Java with Example
- Collections.sort() in Java with Examples
- Arrays class in Java
- Comparable vs Comparator in Java
- Comparator Interface in Java with Examples
- Collections in Java
- Generics in Java