
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 on ArrayList with Java Collections
In order to perform Binary Search on ArrayList with Java Collections, we use the Collections.binarySearch() method.
Declaration βThe java.util.Collections.binarySearch() method is declared as follows β
public static int binarySearch(List list, T key)
The above method returns the position of the key in the list sorted in ascending order. If we use a Comparator c to sort the list, the binarySearch() method will be declared as follows β
public static int binarySearch(List list, T key, Comparator c)
If key is not present, the it returns ((insertion point) + 1) *(-1).
Let us see a program to perform binarySearch() on ArrayList β
Example
import java.util.*; public class Example { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(7); int pos = Collections.binarySearch(list, 1); // 1 is present at 0th index System.out.println(pos); pos = Collections.binarySearch(list, 5); /* since 5 is not present and it would be inserted at index 2 the method returns (-1)*() */ System.out.println(pos); } }
Output
0 -3
Advertisements