English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à exécuter l'algorithme de tri par fusion en Java.
Avant d'apprendre l'algorithme de tri par fusion en Java, assurez-vous que vous comprenez le principe de base de cet algorithme.
import java.util.Arrays; //Tri par fusion en Java class Main { //Fusionner les deux sous-arrays L et M dans l'array void merge(int array[], int p, int q, int r) { int n1 = q - p + 1; int n2 = r - q; int L[] = new int[n1]; int M[] = new int[n2]; //Remplir les deux arrays de gauche et de droite for (int i = 0; i < n1; i++{ L[i] = array[p + i]; } for (int j = 0; j < n2; j++{ M[j] = array[q + 1 + j]; } //Gérer les indices actuels des sous-arrays et de l'array principal int i, j, k; i = 0; j = 0; k = p; //Jusqu'à ce que nous atteignions l'un ou l'autre extrémité de L ou M, en choisissant le plus grand //Les éléments L et M, et les placer à la bonne position dans A[p..r]. //Trier en ordre décroissant //Utiliser if(L[i] >= <[j]) while (i < n1 && j < n2) { if (L[i] <= M[j]) { array[k] = L[i]; i++; } else { array[k] = M[j]; j++; } k++; } // Lorsque les éléments de L ou M sont épuisés // Ajouter les autres éléments restants dans A[p..r] while (i < n1) { array[k] = L[i]; i++; k++; } while (j < n2) { array[k] = M[j]; j++; k++; } } // Diviser l'array en deux sous-arrays, les trier et les fusionner void mergeSort(int array[], int gauche, int droite) { if (gauche < droite) { //m est le point où l'array est divisé en deux sous-arrays int milieu = (gauche + à droite) / 2; //Appel récursif pour chaque sous-tableau mergeSort(array, à gauche, au milieu); mergeSort(array, à droite); + 1, à droite); //Merge sorted subarrays merge(array, left, mid, right); } } public static void main(String args[]) { //Create an unsorted array int[] array = { 6, 5, 12, 10, 9, 1 }; Main ob = new Main(); //Call the mergeSort() method //Pass parameters: array, first index, and last index ob.mergeSort(array, 0, array.length - 1); System.out.println("Sorted array:"); System.out.println(Arrays.toString(array)); } }
Output1
Unsorted array: [6, 5, 12, 10, 9, 1] Sorted array: [1, 5, 6, 9, 10, 12]
In this case, the elements of the array are sorted in ascending order. If you want to sort the elements in descending order, you can change the code inside the first while loop of the merge() method as follows:
Replace the less than sign with greater than if (L[i] >= M[j]) {