Way2Java

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

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); 
  }
}


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.