Une classe C# solution du problème :Le sous programme C# implantant l'algorithme de tri rapide :
static int partition (int G, int D )
{ // partition / méthode de Sedgewick
int i, j, piv, temp;
piv = table[D];
i = G-1;
j = D;
do {
do i++; while (table[i]<piv);
do j--; while (table[j]>piv);
temp = table[i];
table[i] = table[j];
table[j] = temp;
}while(j>i);
table[j] = table[i];
table[i] = table[D];
table[D] = temp;
return i;
}
static void QSort (int G, int D )
{ // tri rapide, sous-programme récursif
int i;
if (D>G) {
i = partition(G,D);
QSort ( G , i-1 );
QSort ( i+1 , D );
}
}
Une classe complète permettant l'exécution du sous-programme précédent :
using System;
namespace CsExosAlgo1
{
class ApplicationTriQSort {
static int[] table; // le tableau à trier
static void AfficherTable ( ) {
// Affichage du tableau sans les sentinelles
int n = table.Length-2;
for ( int i = 1; i <= n; i++)
System.Console.Write (table[i]+" , ");
System.Console.WriteLine ( );
}static void InitTable ( ) {
/* La cellule de rang 0 contient une sentinelle minimale,
la cellule de rang 0 contient une sentinelle maximale (tri sur 19 éléments)
*/
int[ ] tableau = { Int32.MinValue , 68 , 2 , 61 , 81 , 2 , 27 , 10 , 79 , 5 , 70 ,
33 , 72 , 38 , 49 , 49 , 4 , 69 , 18 , 20, Int32.MaxValue };
table = tableau;
}static void main(String[ ] args) {
InitTable ( );
int n = table.Length-2;
System.out.println("Tableau initial :");
AfficherTable ( );
QSort(1,n);
System.out.println("Tableau une fois trié :");
AfficherTable ( );
System.Console.Read ( );
}}
static int partition (int G, int D )
{ // partition / Sedgewick /
int i, j, piv, temp;
piv = table[D];
i = G-1;
j = D;
do {
do i++; while (table[i]<piv);
do j--; while (table[j]>piv);
temp = table[i];
table[i] = table[j];
table[j] = temp;
}while(j>i);
table[j] = table[i];
table[i] = table[D];
table[D] = temp;
return i;
}static void QSort (int G, int D )
{ // tri rapide, sous-programme récursif
int i;
if (D>G) {
i = partition(G,D);
QSort(G,i-1);
QSort(i+1,D);
}
}
}
Source recopiable (cliquez sur le lien)
Tableau initial :
68 , 2 , 61 , 81 , 2 , 27 , 10 , 79 , 5 , 70 , 33 , 72 , 38 , 49 , 49 , 4 , 69 , 18 , 20Tableau une fois trié :
2 , 2 , 4 , 5 , 10 , 18 , 20 , 27 , 33 , 38 , 49 , 49 , 61 , 68 , 69 , 70 , 72 , 79 , 81