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 email@example.com. 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.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.builtcount() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java lang.Long.byteValue() method in Java with Examples
- Java.util.BitSet class in Java with Examples | Set 1
- Java.util.Collections.frequency() in Java with Examples
- Java Clock withZone() method in Java with Examples
- Java Clock tickMinutes() method in Java with Examples