
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Perform Binary Search in Java Using Collections.binarySearch
Binary Search can be performed in Java using the method java.util.Collections.binarySearch(). This method requires two parameters i.e. the list in which binary search is to be performed and the element that is to be searched. It returns the index of the element if it is in the list and returns -1 if it is not in the list.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Demo { public static void main(String args[]) { List aList = new ArrayList(); aList.add("James"); aList.add("George"); aList.add("Bruce"); aList.add("Susan"); aList.add("Martha"); Collections.sort(aList); System.out.println("The sorted ArrayList is: " + aList); int index = Collections.binarySearch(aList, "Martha"); System.out.println("Element Martha is at index: " + index); index = Collections.binarySearch(aList, "Amy"); System.out.println("Element Amy is at index: " + index); } }
The output of the above program is as follows −
The sorted ArrayList is: [Bruce, George, James, Martha, Susan] Element Martha is at index: 3 Element Amy is at index: -1
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The ArrayList elements are sorted using Collections.sort(). A code snippet which demonstrates this is as follows −
List aList = new ArrayList(); aList.add("James"); aList.add("George"); aList.add("Bruce"); aList.add("Susan"); aList.add("Martha"); Collections.sort(aList);
The sorted ArrayList is displayed and then Collections.binarySearch() is used to find if the elements “Martha” and “Amy” are available in the LinkedList or not. A code snippet which demonstrates this is as follows −
System.out.println("The sorted ArrayList is: " + aList); int index = Collections.binarySearch(aList, "Martha"); System.out.println("Element Martha is at index: " + index); index = Collections.binarySearch(aList, "Amy"); System.out.println("Element Amy is at index: " + index);