Sorting Strings

For our last example in this chapter, you'll learn how to sort strings alphabetically. The type of sort being demonstrated is a called a bubble sort. A bubble sort is easy to comprehend but relatively slow.

It works by repeatedly looping through the list of items, comparing two at a time. If item b should come before item a, their places are switched. As you might guess, to make the comparison on strings, we will use the strcmp() function.

We say this is a slow sort because it requires a pair of nested for loops that bubbles every item through the entire list of items. If you had a list of, say, 10 words, a total of 90 (9 * 10) comparisons would need to be made.

Aside from the type of sort being used, a more important consideration ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.