Arrays.binarySearch(int[], int) in Java

Arrays.binarySearch(int[], int): This method is available in java.util.Arrays class of Java.

Syntax:

int java.util.Arrays.binarySearch(int[] a, int key)

This method takes two arguments, one of type int array and the other of type int as its parameters. This method searches the specified array of ints for the specified value.

Note: The array must be sorted.

Parameters: Two parameters are required for this method.

a: the array to be searched.

key: the value to be searched for.

Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).

Note: 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.

Exceptions: NA

Approach

Java

import java.util.Arrays;

public class ArraysbinarySearchint {
    public static void main(String[] args) {

        // for type int
        int intArray[] = { 1, 3, 4, 5, 6, 7 };
        int intKey = 5;

        // to ensure array is sorted
        Arrays.sort(intArray);
        System.out.println(Arrays.binarySearch(intArray,
intKey));

    }
}

Output:

3

No comments:

Post a Comment