Tri itératif

Trier un tableau d'entiers

#include <stdio.h>
#include <stdlib.h>

void tri( int t[], int n)
//un tableau et le nombre d'éléments de ce tableau
{
int temp, k1, k2;
for (k1=0;k1<n;k1++)
for (k2=0;k2<n;k2++) //nous modifierons k2=0; en K2=k1+1;
if (t[k1]<t[k2])
{
temp=t[k1];
t[k1]=t[k2];
t[k2]=temp;
}
}

Contents Haut

Modularité

Nous pouvons découper le programme de tri en sous-fonctions:

  • Comparer deux éléments.
  • Permuter deux éléments.

Comparer deux entiers

int compare(int x, int y)
{ return x-y ; }

Valeurs retournées:

  • <0 si x<y
  • 0   si x=y
  • >0 si x>y

Permuter deux entiers

Permutation par les pointeurs (langage C)

void permute(int *x, int *y)
{
int w ;
w=*x;
*x=*y;
*y=w;
}

Permutation par référence (langage C++)

void permute(int &x, int &y)
{
int w ;
w=x;
x=y;
y=w;
}

Sniplets pour trier un tableau

Trier un tableau en C

void tri( int t[], int n)
{
int p, temp, k1, k2;
for (k1=0;k1<n;k1++)
{
p=k1;
for (K2=k1+1;k2<n;k2++)
if ( compare(t[k1],t[k2]) >0 ) {p=k2;}
permute(&t[k1], &t[k2]);
}
}

Trier un tableau en C++

void tri( int t[], int n)
{
int p, temp, k1, k2;
for (k1=0;k1<n;k1++)
{
p=k1;
for (K2=k1+1;k2<n;k2++)
if ( compare(t[k1],t[k2]) >0 ) {p=k2;}
permute(t[k1], t[k2]);
}
}

Contents Haut

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 12/03/2003, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/c-trier-tableau.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.