Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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

 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
Updated on: 2020-06-25T14:35:34+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements