binarySearch() – search array

Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

Code Explanation
LineDescription
5Declaration and initialization of the array myArray with the values 6, 1, 1, 4, 9, 1, 3, 7 and 1
7The sort() Method sorts the array in ascending order
8Returns the index of the specified number.
import java.util.Arrays;

public class ArrayMethods {
    public static void main(String[] args) {
        int[] myArray = { 6, 1, 1, 4, 9, 1, 3, 7, 1 };

        Arrays.sort(myArray);
        System.out.print(Arrays.binarySearch(myArray, 3));
    }
}
Output
4