Q: HOW DO I... sort an array of strings?
A: Sorting jobs come in all sizes. One of the most common is simply sorting an array of strings. Unless the array is very large, the standard qsort() function is often inefficient for such tasks. In such situations, you might consider the Shell sort presented in this Snippet. Call it with only two
arguments, a pointer to the string array to sort and the number of strings in the array.
/*
** strsort() -- Shell sort an array of string pointers via strcmp()
** public domain by Ray Gardner Denver, CO
*/
#include <string.h>
#include <stddef.h>
void strsort (char **array, size_t array_size)
{
size_t gap, i, j;
char **a, **b, *tmp;
for (gap = 0; ++gap < array_size; )
gap *= 2;
while (gap /= 2)
{
for (i = gap; i < array_size; i++)
{
for (j = i - gap; ;j -= gap)
{
a = array + j;
b = a + gap;
if (strcmp(*a, *b) <= 0)
break;
tmp = *a;
*a = *b;
*b = tmp;
if (j < gap)
break;
}
}
}
}
More C Snippets
- Determining a file's size
- Rounding floating-point values
- Sorting an array of strings
- Computing the wind chill factor
- Timers and default actions
All the code in C Snippets is either public domain or freeware and may therefore freely be used by the C programming community without restrictions. In most cases, if the original author is someone other than myself he or she will be identified. Thanks to all who have contributed to this collection over the years. I hope Dr. Dobb's readers will find these useful.
— Bob Stout
rbs@snippets.org


