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

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

Syntax:

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

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

        // for type float
        float floatArray[] = { 13.4f, 14.5f, 56.6f, 78.78f };
        float floatKey = 14.5f;

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

Output:

1


No comments:

Post a Comment