Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Arrays.binarySearch — searching a sorted array

Arrays.binarySearch searches a sorted array. It returns the matching index or a negative result encoding the insertion point.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

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

Arrays.binarySearch(int[] a, int key) from java.util.Arrays requires an array sorted in ascending order. Results for unsorted data are undefined.

A result >= 0 is the zero-based index of a matching element. With duplicates, which matching index is returned is not guaranteed.

A negative result r encodes the insertion point: -r - 1. This is the index of the first element greater than key, or a.length. Do not check only r == -1: other negative results also mean the value is absent.

Examples

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] values = {10, 20, 30, 40};
        int found = Arrays.binarySearch(values, 30);
        int missing = Arrays.binarySearch(values, 25);
        System.out.println(found);
        System.out.println(missing);
        System.out.println(-missing - 1);
    }
}

Result

2
-3
2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources