Java Utility Library

Java Arrays - binarySearch() Method



The java.util.Arrays.binarySearch() method is used to search a range of the specified array of floats for the specified value using the binary search algorithm. The range must be sorted (as by the sort(float[], int, int) method) prior to making this call. If it is not sorted, the results are undefined. If the range contains multiple elements with the specified value, there is no guarantee which one will be found.

Syntax

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

Parameters

a Specify the array to be searched.
fromIndex Specify the index of the first element (inclusive) to be searched.
toIndex Specify the index of the last element (exclusive) to be searched.
key Specify the value to be searched for.

Return Value

Returns index of the search key, if it is contained in the array within the specified range; otherwise, (-(insertion point) - 1). The insertion point is defined as 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

  • Throws IllegalArgumentException, if fromIndex > toIndex
  • Throws ArrayIndexOutOfBoundsException, if fromIndex < 0 or toIndex > a.length

Example:

In the example below, the java.util.Arrays.binarySearch() method is used to search and return the index of the search key in the given range of array of floats.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a float array
    float Arr[] = {10f, 25f, 5f, -10f, -30f, 0f, 100f};

    //sorting the specified range of float array, 
    //specified range or whole array must be
    //sorted before using binary search
    Arrays.sort(Arr, 2, 7);

    //printing the sorted array
    System.out.println("After sorting the specified range"); 
    System.out.print("Arr contains:"); 
    for(float i: Arr)
      System.out.print(" " + i);

    //returning the index number of searched key
    float val = -10f;
    int idx = Arrays.binarySearch(Arr, 2, 7, val);
    System.out.print("\nThe index number of -10f is: " + idx);  
  }
}

The output of the above code will be:

After sorting the specified range
Arr contains: 10.0 25.0 -30.0 -10.0 0.0 5.0 100.0
The index number of -10f is: 3

❮ Java.util - Arrays