Java Search element with binarySearch()

Java Search element with binarySearch()


There comes binarySearch() method to search for an element in a data structure. The name is derived so because the searching algorithm followed by the designers is binary search. binarySearch() is overloaded that takes the List object and the element to be searched as parameters; and the other using a Comparator object.

Following are the two methods of binary search and their signature.

  • static int binarySearch(List list1, Object obj1): Searches the obj1 in the list list1. Returns the index number of the element obj1. Before applying this method, the elements must be sorted earlier with sort() method; else unexpected results may be obtained at different times of execution.
  • static int binarySearch(List list1, Object obj1, Comparator comp): Searches the element obj1 in the list list1. Returns the index number of obj1. Before applying this method, the elements must be sorted earlier with sort(List, Comparator) method; else unexpected results may be obtained at different times of execution

Note: One precaution to be taken with binarchSearch() is this method should be applied on sorted elements only. That is, first sort() method should be called and then later binarchSearch().

The following program uses the first method and on the later (using Comparator), many programs are given as in Comparator Example and Comparable vs. Comparator.

Example on Java Search element with binarySearch()


Java Search element with binarySearch()
Output screen on Java Search element with binarySearch()

ArrayList myList = new ArrayList();
myList.add(50);

An ArrayList object myList is created and added a few elements with add() method inherited from List interface.

Collections.sort(myList);
int num = Collections.binarySearch(myList, 40);

To the binarySearch() method, the List object myList and the element 40 to be searched is passed as parameters. The method returns 2, the index number of 40 in the list of elements. Elements indexing start from 0. But before this method is called, the elements are sorted with sort() method.

Same method binarySearch() also available in class Arrays to shuffle array elements.

Note: Even though, the sort() is to be called before binarySearch() as per the specification, even without calling also it worked on my system with JDK 1.6. Try on your system.

Leave a Reply

Your email address will not be published. Required fields are marked *