Sorting Strings : String Sort « String « C Tutorial






#include <stdio.h>
  #include <string.h>

  /* A Quicksort for strings. */
  void quick_string(char items[][10], int count)
  {
    qs_string(items, 0, count-1);
  }

  int qs_string(char items[][10], int left, int right)
  {
    register int i, j;
    char *x;
    char temp[10];

    i = left; j = right;
    x = items[(left+right)/2];

    do {
      while((strcmp(items[i],x) < 0) && (i < right)) i++;
      while((strcmp(items[j],x) > 0) && (j > left)) j--;
      if(i <= j) {
        strcpy(temp, items[i]);
        strcpy(items[i], items[j]);
        strcpy(items[j], temp);
        i++; j--;
     }
    } while(i <= j);

    if(left < j) qs_string(items, left, j);
    if(i < right) qs_string(items, i, right);
  }

  char str[][10] = { "one",
                     "two",
                     "three",
                     "four"
                   };
  int main(void)
  {
    int i;

    quick_string(str, 4);

    for(i=0; i<4; i++) printf("%s ", str[i]);

    return 0;
  }








3.12.String Sort
3.12.1.The functional approach to string sorting
3.12.2.Sorting Strings