Java Arrays binarySearch() Method



Description

The Java Arrays binarySearch(Object[] a, Object key) method searches the specified array of Objects for the specified value using the binary search algorithm. The array must be sorted according to natural ordering of the objects before making this call. If it is not sorted, the results are undefined.

Declaration

Following is the declaration for java.util.Arrays.binarySearch(Object[] a, Object key) method

public static int binarySearch(Object[] a, Object key)

Parameters

  • a − This is the array to be searched.

  • key − This is the value to be searched for.

Return Value

This method returns index of the search key, if it is contained in the array, else it returns (-(insertion point) - 1). The insertion point is the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

Exception

  • ClassCastException − if the search key is not comparable to the elements of the array.

Java Arrays binarySearch(Object[] a, int fromIndex, int toIndex, Object key) Method

Description

The Java Arrays binarySearch(Object[] a, int fromIndex, int toIndex, Object key) method searches a range of the specified array of Objects for the specified value using the binary search algorithm. The range must be sorted according to natural ordering of the objects before making this call.If it is not sorted, the results are undefined.

Declaration

Following is the declaration for java.util.Arrays.binarySearch(Object[] a, int fromIndex, int toIndex, Object key) method

public static int binarySearch(Object[] a, int fromIndex, int toIndex, Object key)

Parameters

  • a − This is the array to be searched.

  • fromIndex − This is the index of the first element (inclusive) to be searched.

  • toIndex − This is the index of the last element (exclusive) to be searched.

  • key − This is the value to be searched for.

Return Value

This method returns index of the search key, if it is contained in the array, else it returns (-(insertion point) - 1). The insertion point is the point at which the key would be inserted into the array; the index of the first element in the range greater than the key, or toIndex if all elements in the range are less than the specified key.

Exception

  • ClassCastException − if the search key is not comparable to the elements of the array.

  • IllegalArgumentException − if fromIndex > toIndex

  • ArrayIndexOutOfBoundsException − if fromIndex < 0 or toIndex > a.length

Performing Binary Search on Object Array Example

The following example shows the usage of Java Arrays binarySearch(Object[], key) method. First, we've created an array of Student objects, sorted and printed them. Then binary search is performed on a value and result is printed.

package com.tutorialspoint;
import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {

      // initializing unsorted Object array
      Student studentsArr[] = new Student[]{new Student(1, "Julie"), new Student(3, "Adam"), new Student(2, "Robert")};

      // sorting array
      Arrays.sort(studentsArr);

      // let us print all the elements available in list
      System.out.println("The sorted Object array is:");
      for (Student student : studentsArr) {
         System.out.println("Student = " + student);
      }

      // entering the student to be searched
      Student searchVal = new Student(1, "Julie");
      int retVal = Arrays.binarySearch(studentsArr,searchVal);
      System.out.println("The index of student Julie is : " + retVal);
   }
}
class Student implements Comparable<Student> {
   int rollNo;
   String name;
   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }   
   @Override
   public boolean equals(Object obj) {
      Student s = (Student)obj;
      return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name);
   }
   @Override
   public int compareTo(Student student) {
      return this.rollNo - student.rollNo;
   }
}

Output

Let us compile and run the above program, this will produce the following result −

The sorted Object array is:
Student = [ 1, Julie ]
Student = [ 2, Robert ]
Student = [ 3, Adam ]
The index of student Julie is : 0

Performing Binary Search on Object Sub-Array Example

The following example shows the usage of Java Arrays binarySearch(Object[], fromIndex, toIndex, key) method. First, we've created an array of Student objects, sorted and printed them. Then binary search is performed on a value on sub array and result is printed.

package com.tutorialspoint;
import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {

      // initializing unsorted Object array
      Student studentsArr[] = new Student[]{new Student(1, "Julie"), new Student(3, "Adam"), new Student(2, "Robert")};

      // sorting array
      Arrays.sort(studentsArr);

      // let us print all the elements available in list
      System.out.println("The sorted Object array is:");
      for (Student student : studentsArr) {
         System.out.println("Student = " + student);
      }

      // entering the object to be searched
      Student searchVal = new Student(1, "Julie");

      // entering the range of index
      int retVal = Arrays.binarySearch(studentsArr,0,1,searchVal);
      System.out.println("The index of student Julie is : " + retVal);
   }
}
class Student implements Comparable<Student> {
   int rollNo;
   String name;
   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }   
   @Override
   public boolean equals(Object obj) {
      Student s = (Student)obj;
      return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name);
   }
   @Override
   public int compareTo(Student student) {
      return this.rollNo - student.rollNo;
   }
}

Output

Let us compile and run the above program, this will produce the following result −

The sorted Object array is:
Student = [ 1, Julie ]
Student = [ 2, Robert ]
Student = [ 3, Adam ]
The index of student Julie is : 0

Performing Binary Search on Object Array for Non-Existent Object Example

The following example shows the usage of Java Arrays binarySearch(Object[], key) method. First, we've created an array of Student objects, sorted and printed them. Then binary search is performed on a value which is not present in the array and result is printed .

package com.tutorialspoint;
import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {

      // initializing unsorted Student array
      Student studentsArr[] = new Student[]{new Student(1, "Julie"), new Student(3, "Adam"), new Student(2, "Robert")};

      // sorting array
      Arrays.sort(studentsArr);

      // let us print all the elements available in list
      System.out.println("The sorted Student array is:");
      for (Student student : studentsArr) {
         System.out.println("Student = " + student);
      }

      // entering the value to be searched
      Student searchVal = new Student(4, "Jene");
      int retVal = Arrays.binarySearch(studentsArr,searchVal);
      System.out.println("The index of student Jene is : " + retVal);
   }
}
class Student implements Comparable<Student> {
   int rollNo;
   String name;
   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }   
   @Override
   public boolean equals(Object obj) {
      Student s = (Student)obj;
      return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name);
   }
   @Override
   public int compareTo(Student student) {
      return this.rollNo - student.rollNo;
   }
}

Output

Let us compile and run the above program, this will produce the following result −

The sorted Student array is:
Student = [ 1, Julie ]
Student = [ 2, Robert ]
Student = [ 3, Adam ]
The index of student Jene is : -4
java_util_arrays.htm
Advertisements