English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à exécuter l'algorithme de tri à bulles en Java.
Avant d'étudier l'algorithme de tri à bulles en Java, assurez-vous que vous comprenez le principe de fonctionnement de l'algorithme de tri à bulles.
//Importation des classes import java.util.Arrays; import java.util.Scanner; class Main { //Créez un objet scanner. //Accepte l'entrée de l'utilisateur Scanner input = new Scanner(System.in); //Méthode d'exécution du tri à bulles void bubbleSort(int array[]) { int size = array.length; //Utilisé pour le tri croissant ou décroissant System.out.println("Choisissez l'ordre de tri:"); System.out.println("1Représente l'ordre croissant\n2Représente l'ordre décroissant); int sortOrder = input.nextInt(); //Exécutez la boucle deux fois //La première boucle accède à chaque élément de l'array for (int i = 0; i < size - 1; i++) //La deuxième boucle effectue des comparaisons à chaque itération for (int j = 0; j < size - i - 1; j++) //Triez l'array par ordre croissant if (sortOrder == 1]) { //Comparez les éléments adjacents if (array[j] > array[j + 1]) { // Si l'élément de gauche est supérieur à l'élément de droite, échangez-les int temp = array[j]; array[j] = array[j + 1]; array[j + 1]=temp; } } //Triez l'array par ordre décroissant else { // Comparez les éléments adjacents if (array[j] < array[j + 1]) { //Si l'élément de gauche est inférieur à l'élément de droite, échangez-les int temp = array[j]; array[j] = array[j + 1]; array[j + 1]=temp; } } } //main method public static void main(String args[]) { //Create an array int[] data = { -2, 45, 0, 11, -9 }; //Create an object of the Main class Main bs = new Main(); //Call the bubbleSort method using the object bs //Pass the array as a method parameter bs.bubbleSort(data); System.out.println("Array sorted in ascending order:"); //Call Arrays class toString() //Convert data to a string System.out.println(Arrays.toString(data)); } }
Output 1
Select sorting order: 1 Indicates ascending order 2 Indicates descending order 1 Sorted array: [-9, -2, 0, 11, 45]
In this case, we enter 1。Therefore, the program sorts the array in ascending order.
Output 2
Select sorting order: 1 Indicates ascending order 2 Indicates descending order 2 Sorted array: [45, 11, 0, -2, -9]
In this case, we enter 2 。Therefore, the program sorts the array in descending order.
Note:We have usedJava Scanner classGet input from the user.