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 comparable 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
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.