Quicksorting Strings

The quicksort deftly handles vast quantities of values. It can also sort strings, but that’s where things can get weird.

If you’re coding your own quicksort function, then you can code a string comparison routine within that function. When you use the C Library’s qsort() function, however, the issue becomes how to craft the proper compare() function.

The following code creates an array of 15 strings. I’ve used array notation, because it’s a big easier to follow when using the qsort() function. The constant C holds the number of array elements:

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

#define C 15

int compare(const void *a, const void *b);

int main()
{
    char crew[C][8] = {
        "Thorin",   "Fili", "Kili",
        "Bilbo",    "Dori", "Balin",
        "Dwalin",   "Ori",  "Gloin",
        "Bifur",    "Nori", "Bofur",
        "Bombur",   "Oin",  "Gandalf"
    };
    int x;

    /* print original strings */
    printf("Original: ");
    for(x=0;x<C;x++)
        printf("%s ",crew[x]);
    putchar('\n');

    /* quicksort the list */
    qsort(crew,C,8,compare);

    /* print sorted strings */
    printf("  Sorted: ");
    for(x=0;x<C;x++)
        printf("%s ",crew[x]);
    putchar('\n');

    return(0);
}

int compare(const void *a, const void *b)
{
    return( strcmp((char *)a,(char *)b) );
}

The qsort() function at Line 27 uses 8 as the size of each item to be sorted, which is the second element in the two-dimensional string array (Line 11). The compare() function uses the strcmp() function to compare both strings. Coincidentally, the strcmp() function returns values identical to what must be returned for the compare() function: less than zero, zero, or greater than zero, depending on how the strings compare.

Here’s sample output:

Original: Thorin Fili Kili Bilbo Dori Balin Dwalin Ori Gloin Bifur Nori Bofur Bombur Oin Gandalf 
  Sorted: Balin Bifur Bilbo Bofur Bombur Dori Dwalin Fili Gandalf Gloin Kili Nori Oin Ori Thorin 

While this code works, the drawback is that not every array of strings is crafted by using a two-dimensional array. Most string arrays are pointer arrays, which use the dratted double asterisk, **. I’ll cover how to quicksort that monster in next week’s Lesson.

Leave a Reply