logo

Tri par insertion en Java

Nous pouvons créer un programme Java pour trier les éléments du tableau en utilisant le tri par insertion. L'insertion n'est bonne que pour les petits éléments car elle nécessite plus de temps pour trier un grand nombre d'éléments.

tri par insertion

Voyons un programme Java simple pour trier un tableau à l'aide d'un algorithme de tri par insertion.

variable bash
 public class InsertionSortExample { public static void insertionSort(int array[]) { int n = array.length; for (int j = 1; j <n; j++) { int key="array[j];" i="j-1;" while ( (i> -1) &amp;&amp; ( array [i] &gt; key ) ) { array [i+1] = array [i]; i--; } array[i+1] = key; } } public static void main(String a[]){ int[] arr1 = {9,14,3,2,43,11,58,22}; System.out.println(&apos;Before Insertion Sort&apos;); for(int i:arr1){ System.out.print(i+&apos; &apos;); } System.out.println(); insertionSort(arr1);//sorting array using insertion sort System.out.println(&apos;After Insertion Sort&apos;); for(int i:arr1){ System.out.print(i+&apos; &apos;); } } } </n;>

Sortir:

 Before Insertion Sort 9 14 3 2 43 11 58 22 After Insertion Sort 2 3 9 11 14 22 43 58