Skip to Content

Perform Binary Search on Java ArrayList Example

  1. /*
  2.   Perform Binary Search on Java ArrayList Example
  3.   This java example shows how to search an element of Java ArrayList
  4.   using binarySearch method of Collections class. binarySearch method uses
  5.   binary search algorithm to search an element.
  6. */
  7.  
  8. import java.util.ArrayList;
  9. import java.util.Collections;
  10.  
  11. public class BinarySearchArrayListExample {
  12.  
  13.   public static void main(String[] args) {
  14.     //create an ArrayList object
  15.     ArrayList arrayList = new ArrayList();
  16.  
  17.     //Add elements to Arraylist
  18.     arrayList.add("1");
  19.     arrayList.add("4");
  20.     arrayList.add("2");
  21.     arrayList.add("5");
  22.     arrayList.add("3");
  23.    
  24.     /*
  25.       To Search an element of Java ArrayList using binary search algorithm use,
  26.       static int binarySearch(List list, Object element) method of Collections class.
  27.      
  28.       This method returns the index of the value to be searched, if found in the
  29.       ArrayList.
  30.       Otherwise it returns (- (X) - 1)
  31.       where X is the index where the the search value would be inserted.
  32.       i.e. index of first element that is grater than the search value
  33.       or ArrayList.size(), if all elements of an ArrayList are less
  34.       than the search value.
  35.      
  36.       Please note that the ArrayList MUST BE SORTED before it can be searched
  37.       using binarySearch method.
  38.     */
  39.    
  40.     //First sort an ArrayList using sort method of Collections class
  41.     Collections.sort(arrayList);
  42.     System.out.println("Sorted ArrayList contains : " + arrayList);
  43.    
  44.     //search an element using binarySearch method of Collections class
  45.     int index = Collections.binarySearch(arrayList,"4");
  46.    
  47.     System.out.println("Element found at : " + index);
  48.   }
  49. }
  50.  
  51. /*
  52. Output would be
  53. Sorted ArrayList contains : [1, 2, 3, 4, 5]
  54. Element found at : 3
  55. */