FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
C++
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
August 27, 2009
C Snippet #3

Bob Stout
Sorting an array of strings

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

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

TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK