user3706129
user3706129

Reputation: 229

Sorting arrays in c

It is common task to sort an array of integer using qtsort() , but it is possible to sort sort array of strings lets say

{"One","two","three","all"}  or even take it higher sort "string number"? e.g
{"50.5>ahoh","45>Two","50>here"}

Or are we limited to sorting array of ints?

Upvotes: 1

Views: 203

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42899

It is possible to sort the array of strings lexicographically if you use the following custom comparator that uses strcmp:

int cmpfunc(void *a, void *b) {
  const char **ia = (const char **)a;
  const char **ib = (const char **)b;
  return strcmp(*ia, *ib);
}

int main() {
   int n;
   char *values[] = { "88", "56", "100", "2", "25" };

   printf("Before sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) 
   {
      printf("%s ", values[n]);
   }

   qsort(values, 5, sizeof(char*), cmpfunc);

   printf("\nAfter sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) 
   {   
      printf("%s ", values[n]);
   }

   return(0);
}

Live Demo

Alternatively, if you want a custom ordering you can define in the same fashion your custom comparator to compare the input strings accordingly.

Upvotes: 4

Related Questions