Tri de sélection dans le programme Java avec exemple

Anonim

Comment fonctionne le tri par sélection?

Le tri par sélection implémente un algorithme de tri simple comme suit:

  • L'algorithme recherche à plusieurs reprises l'élément le plus bas.
  • Permuter l'élément actuel avec un élément ayant la valeur la plus basse
  • À chaque itération / passe de tri de sélection, les éléments sont permutés.

Programme Java pour implémenter le tri par sélection

package com.guru99;classe publique SelectionSortAlgo {public static void main (chaîne a []){int [] myArray = {860,8,200,9};System.out.println ("------ Avant le tri par sélection -----");printArray (myArray);selection (myArray); // tri du tableau en utilisant le tri par sélectionSystem.out.println ("----- Après le tri de sélection -----");printArray (myArray);}sélection de vide statique public (tableau int []){pour (int i = 0; i 

Production:

------Before Selection Sort-----860 8 200 9Sort Pass Number 1Comparing 860 and 8860 is greater than 8Comparing 8 and 200Comparing 8 and 9Swapping Elements: New Array After Swap8 860 200 9Sort Pass Number 2Comparing 860 and 200860 is greater than 200Comparing 200 and 9200 is greater than 9Swapping Elements: New Array After Swap8 9 200 860Sort Pass Number 3Comparing 200 and 860Swapping Elements: New Array After Swap8 9 200 860-----After Selection Sort-----8 9 200 860