/* Tri par selection d'un tableau d'entiers */ import java.util.Random; public class TriSelection { /* Fonction d'affichage des valeurs contenues */ /* dans un tableau de int */ static void affichageTableau(int [] t) { for ( int i = 0 ; i < t.length ; i++ ) { Ecran.formater("%4d",t[i]); } Ecran.sautDeLigne(); } /* Fonction de creation d'un tableau de n int */ /* initialise avec des valeurs croissantes */ static int [] initRandCroissant(int n,long seed) { Random r = new Random(seed); int [] t = new int[n]; t[0] =(int) (r.nextDouble()*10.0); for ( int i = 1 ; i < t.length ; i++ ) { t[i] = t[i-1] + (int) (r.nextDouble()*10.0); } return t; } /* Fonction de creation d'un tableau de n int */ /* initialise avec des valeurs croissantes */ static int [] initRandQuasiCroissant(int n,long seed) { Random r = new Random(seed); int [] t = initRandCroissant(n,seed); int nb = 10; int i1; int i2; int aux; for ( int i = 0 ; i < nb ; i++ ) { i1 =(int) (r.nextDouble()*(n+1)); i2 =(int) (r.nextDouble()*(n+1)); aux = t[i1]; t[i1] = t[i2]; t[i2] = aux; } return t; } /* Fonction de creation d'un tableau de 10 int */ /* initialise avec des valeurs tirees au sort */ /* dans l'intervalle [0,1000[ */ static int [] initRand() { int [] t = new int[10]; for ( int i = 0 ; i < t.length ; i++ ) { t[i] =(int) (Math.random()*1000.0); } return t; } /////////////////////////////////////////////////// /* Fonction de recherche et retour de l'indice */ /* de la valeur maximale d'un tableau d'int */ /* restreint à ses n+1 premieres valeurs */ /* n : L'indice inclus jusqu'auquel la recherche */ /* de valeur maximale est réalisée */ /* t : Le tableau d'int où la recherche */ /* de valeur maximale est réalisée */ static int indiceDuMaximum(int n,int [] t) { int iMax = 0; for ( int i = 1 ; i <= n ; i++ ) { if ( t[i] > t[iMax] ) { iMax = i; } } return iMax; } /* Fonction de tri "par selection" */ /* par ordre croissant des valeurs contenues */ /* dans un tableau d'int */ /* t : Le tableau d'int à trier */ /* par ordre croissant */ static void triSelection(int [] t) { int n = t.length; for ( int i = 1 ; i <= n-1 ; i++ ) { int ind = n-i; int iMax = indiceDuMaximum(ind,t); if ( t[iMax] != t[ind] ) { int aux = t[iMax]; t[iMax] = t[ind]; t[ind] = aux; } } } /////////////////////////////////////////////////// /* Programme principal */ public static void main(String [] args) { int [] t = initRand(); Ecran.afficherln("Tableau initial"); affichageTableau(t); triSelection(t); Ecran.afficherln("Tableau trié"); affichageTableau(t); } }