English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode binarySearch () implémente l'algorithme de recherche binaire pour chercher l'élément passé en paramètre. Si vous souhaitez comprendre comment fonctionne la recherche binaire, veuillez consulter l'algorithme de recherche binaire.
Attention : si nous devons implémenter l'algorithme de recherche binaire en Java, il est préférable d'utiliser la méthode binarySearch() plutôt que de réaliser l'algorithme nous-mêmes.
import java.util.ArrayList; import java.util.Collections; class Main { public static void main(String[] args) { //Create array list 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