Algorithme de tri par insertion dans un programme Java avec exemple

Table des matières:

Anonim

Le tri par insertion est un algorithme de tri simple adapté aux petits ensembles de données. Lors de chaque itération, l'algorithme

  • Supprime un élément d'un tableau
  • Le compare à la plus grande valeur du tableau
  • Déplace l'élément à son emplacement correct.

Voici comment le processus fonctionne graphiquement

Programme JAVA pour trier un tableau à l'aide de l'algorithme de tri par insertion.

package com.guru99;classe publique InsertionSortExample {public static void main (chaîne a []){int [] myArray = {860,8,200,9};System.out.println ("Avant le tri par insertion");printArray (myArray);insertionSort (myArray); // tri du tableau à l'aide du tri par insertionSystem.out.println ("Après le tri par insertion");printArray (myArray);}public static void insertionSort (int arr []){int n = arr.length;pour (int i = 1; i  -1) && (touche arr [j]>)){System.out.println ("Comparaison" + touche + "et" + arr [j]);arr [j + 1] = arr [j];j--;}arr [j + 1] = clé;System.out.println ("Swapping Elements: New Array After Swap");printArray (arr);}}static void printArray (int [] array) {pour (int i = 0; i 

Sortie de code:

Before Insertion Sort860 8 200 9Sort Pass Number 1Comparing 8 and 860Swapping Elements: New Array After Swap8 860 200 9Sort Pass Number 2Comparing 200 and 860Swapping Elements: New Array After Swap8 200 860 9Sort Pass Number 3Comparing 9 and 860Comparing 9 and 200Swapping Elements: New Array After Swap8 9 200 860After Insertion Sort8 9 200 860