Search array element binarySearch()

Arrays.binarySearch() method is useful to find out the index number of an element in the array.

Two methods exist in the Arrays class for the purpose and following are their method signatures

    static int binarySearch(int array1[], int searchNum): Searches the element searchNum in the array array1. This method should be used in combination with sort() method. Before applying this method, the elements of the array should be sorted with sort() method; else unexpected results are expected. This method is overloaded to accept an array of any data type.

  • static int binarySearch(Object array1, Object searchNum, Comparator comp1): It is a modified form of the previous search where the searching is done as per the order set by Comparator comp1. Before applying this method, the elements should be sorted in an order as per the Comparator comp1; else unexpected results are expected. It is just similar to Collections.binarySearch() with comparator.
Following example on Search array element binarySearch() uses the first above method.
import java.util.Arrays;
public  class ArraysBinarySearch
{
  public static void main(String args[])
  {
    String leaders[] = { "Nehruji", "Gandhiji", "Sastryji" };

    System.out.println("Elements of leaders: " + Arrays.toString(leaders));

    //  Arrays.sort(leaders);
    int num1 = Arrays.binarySearch(leaders, "Gandhiji");
    int num2 = Arrays.binarySearch(leaders, "Indiraji");

    System.out.println("\nIndex number of Gandhiji: " + num1);
    System.out.println("Index of Indiraji: " + num2); 
  }
}

Search array element binarySearch()
Output screen of Search array element binarySearch()

String leaders[] = { “Nehruji”, “Gandhiji”, “Sastryji” };
System.out.println(“Elements of leaders: ” + Arrays.toString(leaders));

A string array object leaders is created with three elements. The elements are printed with toString() method of Arrays class.

// Arrays.sort(leaders);

The searching with binarySearch() should be done on sorted elements as per the specifications. But the search returns the index of number of the element on the new sorted array but not on the original array. I have tried without sorting (against specification) but I found the binarySearch() method works nice. For this reason, the above line is placed in comments. You try on your system.

int num1 = Arrays.binarySearch(leaders, “Gandhiji”);
int num2 = Arrays.binarySearch(leaders, “Indiraji”);

Arrays.binarySearch(leaders, "Gandhiji") returns the index number of "Gandhiji" in the array leaders. But searching "Indiraji"”" returns a negative index number (need not be -1) as element "Indiraji" does not exist in the array.

Arrays.binarySearch() is just similar to Collections.binarySearch() which operates on collection classes.

Leave a Comment

Your email address will not be published.