Method Arrays.binarySearch()

Author: Tatyana Milkina

The Arrays.binarySearch() method in Java returns the index of the specified value in a sorted array. If the element is not found, the method returns -(insertion point + 1), where the insertion point is the index where the value would be inserted to maintain the sorted order.

Important: The array must be sorted in ascending order before calling Arrays.binarySearch(). If not, the result is undefined and may produce incorrect values.

import java.util.Arrays;

public class BinarySearchExample1 {
    public static void main(String[] args) {
        int[] array1 = {10, 20, 30, 40};
        int pos1 = Arrays.binarySearch(array1, 20);
        int pos2 = Arrays.binarySearch(array1, 25);
        System.out.println(pos1); // Output: 1
        System.out.println(pos2); // Output: -3
    }
}

Output:

1
-3

In the first case, the method finds the value 20 at index 1. In the second case, the value 25 is not found, but would be inserted at index 2 to maintain the order, so the method returns -3 (i.e. -(2 + 1)).

The Arrays.binarySearch() method can also be used with arrays of other primitive types (like double[], char[]) and with object arrays using comparators.

Binary search is highly efficient with a time complexity of O(log n), making it ideal for large datasets, provided the data is already sorted.

Read also:
Comments