English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The binarySearch() method implements the binary search algorithm to search for the element passed as a parameter. If you want to understand how binary search works, please refer to the binary search algorithm.
Note: If we need to implement the binary search algorithm in Java, it is best to use the binarySearch() method rather than implementing the algorithm ourselves.
import java.util.ArrayList; import java.util.Collections; class Main { public static void main(String[] args) { //Create ArrayList ArrayList<Integer> numbers = new ArrayList<>(); //Add Element numbers.add(4); numbers.add(2); numbers.add(3); Collections.sort(numbers); System.out.println("ArrayList: " + numbers); //Using binarySearch() method int position = Collections.binarySearch(numbers, 3); System.out.println("Position of 3: " + position); } }
Output
ArrayList: [2, 3, 4] Position of 3: 1