Java Utility Library

Java Arrays - binarySearch() Method



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

Syntax

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

Parameters

a Specify the array 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; 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 greater than the key, or a.length if all elements in the array are less than the specified key.

Exception

NA.

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 array of longs.

import java.util.*;

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

    //sorting the long array, array must be
    //sorted before using binary search
    Arrays.sort(Arr);

    //printing the sorted array
    System.out.print("After sorting, Arr contains:"); 
    for(long i: Arr)
      System.out.print(" " + i);

    //returning the index number of searched key
    long val = 25;
    int idx = Arrays.binarySearch(Arr, val);
    System.out.print("\nThe index number of 25 is: " + idx);  
  }
}

The output of the above code will be:

After sorting, Arr contains: -30 -10 5 10 25
The index number of 25 is: 4

❮ Java.util - Arrays