C/C++: Trier une chaîne de caractère avec une fonction recursive

Author:


Download

#include 
#include 
#include 

void tri_recursion(char *elements, int n_gauche, int n_droite)
{
  int i, j;
  char x, y;

  i = n_gauche;
  j = n_droite;
  x = elements[(n_gauche+n_droite)/2];

  do {
    while((elements[i] < x) && (i < n_droite))
       i++;
    while((x < elements[j]) && (j > n_gauche))
       j--;

    if(i <= j) {
      y = elements[i];
      elements[i] = elements[j];
      elements[j] = y;
      i++; j--;
    }
  } while(i <= j);

  if(i < n_droite)
      tri_recursion(elements, i, n_droite);
  if(n_gauche < j)
      tri_recursion(elements, n_gauche, j);

}
int main(void)
{
  char s[255]="asdfasdfasdfasdfasdfasdfasdf";

    tri_recursion(s, 0, strlen(s)-1);
  printf("The sorted string is: %s.", s);

  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *