Une classe C# solution du problème :Le sous programme C# implantant l'algorithme de tri à bulle sur le tableau 'table' :
static void TriBulle ( )
{ // sous-programme de Tri à bulle classique (1..n éléments):
int n = table.Length-1;
for ( int i = n; i>=1; i--)
for ( int j = 2; j<=i; j++)
if (table[j-1] > table[j])
{
int temp = table[j-1];
table[j-1] = table[j];
table[j] = temp;
}
}
Une classe complète permettant l'exécution du sous-programme précédent :
using System;
namespace CsExosAlgo1
{
class ApplicationTriInsert {
static int[] table ; // le tableau à trier, par exemple 19 éléments
static void AfficherTable ( ) {
// Affichage du tableau
int n = table.Length-1;
for ( int i = 1; i <= n; i++)
System.Console.Write (table[i]+" , ");
System.Console.WriteLine ( );
}static void InitTable ( ) {
int[ ] tableau = { 0 ,25, 7 , 14 , 26 , 25 , 53 , 74 , 99 , 24 , 98 ,
89 , 35 , 59 , 38 , 56 , 58 , 36 , 91 , 52 };
table = tableau;
}static void Main(string[ ] args) {
InitTable ( );
System.Console.WriteLine ("Tableau initial :");
AfficherTable ( );
TriBulle ( );
System.Console.WriteLine ("Tableau une fois trié :");
AfficherTable ( );
System.Console.Read();
}}
static void TriBulle ( ) {
// sous-programme de Tri à bulle : on trie les éléments du n°1 au n°19
int n = table.Length-1;
for ( int i = n; i>=1; i--)
for ( int j = 2; j <= i; j++)
if (table[j-1] > table[j]){
int temp = table[j-1];
table[j-1] = table[j];
table[j] = temp;
}
/* Dans le cas où l'on démarre le tableau à l'indice zéro
on change les bornes des indices i et j:
for ( int i = n; i >= 0; i--)
for ( int j = 1; j <= i; j++)
if ....... reste identique
*/
}
}
Source recopiable (cliquez sur le lien)
Tableau initial :
25 , 7 , 14 , 26 , 25 , 53 , 74 , 99 , 24 , 98 , 89 , 35 , 59 , 38 , 56 , 58 , 36 , 91 , 52Tableau une fois trié :
7 , 14 , 24 , 25 , 25 , 26 , 35 , 36 , 38 , 52 , 53 , 56 , 58 , 59 , 74 , 89 , 91 , 98 , 99