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

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

Syntax:

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

This method takes two arguments one of type long array and the another of type long as its parameters. This method searches the specified array of longs 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 ArraysbinarySearchlong {
    public static void main(String[] args) {

        // for type long
        long longArray[] = { 17177, 38199, 499999,
5919911, 698191, 70000989 };
        long longKey = 499999;

        // to ensure array is sorted
        Arrays.sort(longArray);
        System.out.println(Arrays.binarySearch(longArray,
longKey));
    }
}

Output:

2


No comments:

Post a Comment