Java Arrays binarySearch() Method



Description

The Java Arrays binarySearch(T[] a, T key, Comparator<? super T> c) method searches the specified array of Objects for the specified value using the binary search algorithm. The array must be sorted according to specified Comparator before making this call. If it is not sorted, the results are undefined.

Declaration

Following is the declaration for java.util.Arrays.binarySearch(T[] a, T key, Comparator<? super T> c) method

public static <T> int binarySearch​(T[] a, T key, Comparator<? super T> c)

Parameters

  • a − This is the array to be searched.

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

  • c − the comparator by which the array is ordered. A null value indicates that the elements' natural ordering should be used.

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 array contains elements that are not mutually comparable using the specified comparator, or the search key is not comparable to the elements of the array using this comparator.

Java Arrays binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c) Method

Description

The Java Arrays binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c) 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 specified Comparator before making this call. If it is not sorted, the results are undefined.

Declaration

Following is the declaration for java.util.Arrays.binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c) method

public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)

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.

  • c − the comparator by which the array is ordered. A null value indicates that the elements' natural ordering should be used.

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

  • ClassCastException − if the array contains elements that are not mutually comparable using the specified comparator, or the search key is not comparable to the elements of the array using this comparator.

Performing Binary Search on Object Array Example

The following example shows the usage of Java Arrays binarySearch(T[], key, comparator) 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;
import java.util.Comparator;
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")};
      RollNoComparator comparator = new RollNoComparator();
      
      // sorting array
      Arrays.sort(studentsArr, comparator);

      // 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,comparator);
      System.out.println("The index of student Julie is : " + retVal);
   }
}
class 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);
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
class RollNoComparator implements Comparator<Student>{
   @Override
   public int compare(Student o1, Student o2) {
      return o1.getRollNo()-o2.getRollNo();
   }	
}

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(T[], fromIndex, toIndex, key, comparator) 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;
import java.util.Comparator;
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")};
      RollNoComparator comparator = new RollNoComparator();
      
      // sorting array
      Arrays.sort(studentsArr, comparator);

      // 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,0,1,searchVal,comparator);
      System.out.println("The index of student Julie is : " + retVal);
   }
}
class 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);
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
class RollNoComparator implements Comparator<Student>{
   @Override
   public int compare(Student o1, Student o2) {
      return o1.getRollNo()-o2.getRollNo();
   }	
}

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 comparator) 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;
import java.util.Comparator;
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")};

      RollNoComparator comparator = new RollNoComparator();
      
      // sorting array
      Arrays.sort(studentsArr, comparator);

      // 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(4, "Jene");
      int retVal = Arrays.binarySearch(studentsArr,searchVal,comparator);
      System.out.println("The index of student Jene is : " + retVal);
   }
}
class 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);
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
class RollNoComparator implements Comparator<Student>{
   @Override
   public int compare(Student o1, Student o2) {
      return o1.getRollNo()-o2.getRollNo();
   }	
}

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