Java binarySearch()

The binarySearch() method implements the binary search algorithm to search the element passed as an argument. If you want to learn about how binary search works, visit Binary search algorithm.

Note: If we need to implement the binary search algorithm in Java, it is better to use the binarySearch() method rather than implementing the algorithm on our own.


Example: Java binarySearch()

import java.util.ArrayList;
import java.util.Collections;

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

        // Creating an array list
        ArrayList<Integer> numbers = new ArrayList<>();

        // Add elements
        numbers.add(4);
        numbers.add(2);
        numbers.add(3);
        Collections.sort(numbers);
        System.out.println("ArrayList: " + numbers);

        // Using the binarySearch() method
        int position = Collections.binarySearch(numbers, 3);
        System.out.println("Position of 3: " + position);
    }
}

Output

ArrayList: [2, 3, 4]
Position of 3: 1