Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Arrays.binarySearch()

Quickly finds a value in a sorted array by repeatedly halving it.

Available since: Java 1.2

Syntax

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

Parameters

ParameterTypeDescription
aint[], T[], …An array sorted in ascending order.
keyelement typeThe value to find.

Return value

intThe index of the element, or a negative number if it is absent.

Examples

Searching a sorted array:

void main() {
    int[] numbers = {3, 8, 15, 21, 42};
    IO.println(Arrays.binarySearch(numbers, 21));
    IO.println(Arrays.binarySearch(numbers, 10));
}

Output:

3
-3

Notes

If the element is absent, the result is -(insertion point) - 1: for 10 the insertion point is 2, so -3. For an unsorted array the result is undefined — call Arrays.sort() first. For a single search in a small array a plain loop is enough.

See also

  • Arrays.sort() — Sorts an array in place — in ascending order or by a given comparator.
  • String.indexOf() — Finds the position of the first occurrence of a character or a substring.

Related recipes

In the tutorial

  • The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.

Thanks for reading!

Donate to the site — we work hard for you.