Perform Binary Search on ArrayList with Java Collections

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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
raja
Published on 08-Jan-2019 13:10:46
Advertisements