🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Sorting Strings in C
Free C programming course: sort a two-dimensional char array alphabetically with strcmp, trace every swap, and measure what the sort costs.
Sorting strings in C combines three things you have already learned in this free C programming course: the two-dimensional string table, strcmp for ordering, and a whole-row copy to swap. In this lecture we sort a list of peripheral names, trace the algorithm step by step, count the bytes it moves, and discuss why this approach is simple but not cheap. It is a favorite exercise in embedded C programming interviews, so the details matter.
What You Will Learn
- How
strcmporders two strings and what its return sign means - How to write a selection sort over a 2-D char array
- How to swap two rows with a temporary buffer and
memcpy - How to trace a sort and count the bytes copied
- Why case matters when sorting text in ASCII
- Why moving whole rows is expensive
Prerequisites
Complete the earlier lectures in this chapter on the array of strings in C, its padding, and bounded copying. You should know nested for loops and basic sorting ideas. Build everything with gcc -std=c17 -Wall -Wextra.
How strcmp Orders Strings
strcmp(a, b) compares two strings character by character using their character codes. It returns a negative value if a comes before b, zero if they are equal, and a positive value if a comes after b. The exact magnitude is not specified, only the sign, so never compare the result to a particular number such as 1 or -1.
#include <stdio.h>
#include <string.h>
static int sign(int v) { return (v > 0) - (v < 0); }
int main(void)
{
printf("SPI vs SPI : %d\n", sign(strcmp("SPI", "SPI")));
printf("I2C vs SPI : %d\n", sign(strcmp("I2C", "SPI")));
printf("UART vs SPI : %d\n", sign(strcmp("UART", "SPI")));
printf("SPI vs spi : %d\n", sign(strcmp("SPI", "spi")));
printf("SP vs SPI : %d\n", sign(strcmp("SP", "SPI")));
return 0;
}
SPI vs SPI : 0
I2C vs SPI : -1
UART vs SPI : 1
SPI vs spi : -1
SP vs SPI : -1
| Comparison | Result sign | Why |
|---|---|---|
| I2C vs SPI | negative | I has a smaller code than S |
| UART vs SPI | positive | U is larger than S |
| SPI vs spi | negative | Uppercase letters have smaller codes than lowercase in ASCII |
| SP vs SPI | negative | The shorter string ends first, and NUL is smaller than any letter |
The case rule is important: in plain ASCII every uppercase letter sorts before every lowercase one, so "Zeta" would come before "alpha". If you need a dictionary order that ignores case, you must convert or use a case-insensitive comparison function available on your platform.
Sorting an Array of Strings Step by Step
We use a selection sort: for each position i, find the smallest remaining string in positions i to the end, and swap it into place. Selection sort makes at most one swap per position, which suits an expensive swap like a whole-row copy.
The swap
Rows are arrays, so we cannot write a = b. A swap needs a temporary row and three full-width copies:
memcpy(tmp, dev[i], LEN);
memcpy(dev[i], dev[min], LEN);
memcpy(dev[min], tmp, LEN);
The complete program
Save as sortstr.c:
#include <stdio.h>
#include <string.h>
#define COUNT 5
#define LEN 8
static void show(const char list[][LEN], int n)
{
for (int i = 0; i < n; i++)
printf("%s ", list[i]);
printf("\n");
}
int main(void)
{
char dev[COUNT][LEN] = { "UART", "I2C", "SPI", "GPIO", "ADC" };
char tmp[LEN];
size_t copied = 0;
printf("before: ");
show(dev, COUNT);
for (int i = 0; i < COUNT - 1; i++) {
int min = i;
for (int j = i + 1; j < COUNT; j++)
if (strcmp(dev[j], dev[min]) < 0)
min = j;
if (min != i) {
memcpy(tmp, dev[i], LEN);
memcpy(dev[i], dev[min], LEN);
memcpy(dev[min], tmp, LEN);
copied += 3 * LEN;
}
}
printf("after : ");
show(dev, COUNT);
printf("bytes copied while swapping: %zu\n", copied);
return 0;
}
gcc -std=c17 -Wall -Wextra -o sortstr sortstr.c
./sortstr
Expected output:
before: UART I2C SPI GPIO ADC
after : ADC GPIO I2C SPI UART
bytes copied while swapping: 72
Tracing the Sort
Here is what happens at each outer pass of the outer loop, one row per pass.
| Pass i | Smallest in remaining part | Swap | Table afterwards |
|---|---|---|---|
| 0 | ADC (row 4) | row 0 and row 4 | ADC I2C SPI GPIO UART |
| 1 | GPIO (row 3) | row 1 and row 3 | ADC GPIO SPI I2C UART |
| 2 | I2C (row 3) | row 2 and row 3 | ADC GPIO I2C SPI UART |
| 3 | SPI (row 3) | none, already in place | ADC GPIO I2C SPI UART |
Three passes needed a swap, and each swap copies three rows of 8 bytes, which is 24 bytes. Three swaps give 72 bytes, exactly what the program printed.
| Row | Start offset | Contents |
|---|---|---|
| dev[0] | 0 | A D C \0 and padding |
| dev[1] | 8 | G P I O \0 and padding |
| dev[2] | 16 | I 2 C \0 and padding |
| dev[3] | 24 | S P I \0 and padding |
| dev[4] | 32 | U A R T \0 and padding |
The row addresses never changed; only the bytes inside them did. That is the defining property of a 2-D array: the rows are fixed places, so sorting means moving contents between those places.
Cost of Sorting a 2-D String Array
| Aspect | Cost |
|---|---|
| Comparisons | About N(N-1)/2, which is 10 for N = 5 |
| Swaps | At most N-1 |
| Bytes per swap | 3 times LEN, regardless of string length |
| Extra memory | One temporary row of LEN bytes |
Padding also gets copied. A table with a large LEN and short strings spends most of its swap time moving zeros. This is why many embedded codebases sort pointers to strings instead of the strings themselves, a technique you will meet in the next lectures.
Letting qsort do the work
The standard library already contains a sorting routine. qsort takes the base address, the number of elements, the size of one element, and a comparison function. For a 2-D char array the element size is the row width, and each comparison receives pointers to two rows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COUNT 5
#define LEN 8
static int cmp_row(const void *a, const void *b)
{
return strcmp((const char *)a, (const char *)b);
}
int main(void)
{
char dev[COUNT][LEN] = { "UART", "I2C", "SPI", "GPIO", "ADC" };
qsort(dev, COUNT, LEN, cmp_row);
for (int i = 0; i < COUNT; i++)
printf("%s ", dev[i]);
printf("\n");
return 0;
}
ADC GPIO I2C SPI UART
The result is the same as the hand-written version. Writing the loop yourself is still valuable because interviewers ask for it, and because some bare-metal projects avoid pulling in the standard library sort. When you do use qsort, remember that it swaps rows by raw byte copying, so the row width you pass must match the array exactly.
strcpy and a temporary that is too short; comparing dev[j] < dev[min], which compares addresses instead of text; forgetting that strcmp is case sensitive; and sorting a const table, which would try to write to read-only memory.
Best Practices
- Compare with
strcmpand test only the sign of the result. - Use
sizeofor a named constant for the row width when swapping. - Pick selection sort when swaps are expensive and N is small.
- Document whether ordering is case sensitive.
- For large tables, avoid moving whole rows; sort an index or pointer array.
Performance and security notes
For a handful of names the cost is trivial, but the pattern is quadratic in comparisons, so it does not scale to thousands of entries. On a small MCU, doing a one-time sort at boot is often fine; sorting inside an interrupt handler is not. Security-wise, a temporary buffer smaller than the row would let memcpy overrun the stack, so size it from the same constant as the table.
Summary and Key Takeaways
strcmpreturns a negative, zero or positive value; rely on the sign only.- Uppercase sorts before lowercase in ASCII.
- Sorting a 2-D char array means swapping row contents with a temporary row.
- Each swap copies three full rows, padding included.
- Selection sort limits swaps to at most N-1.
Conclusion
You wrote and traced a complete string sort and measured its byte cost. The takeaway is both practical and conceptual: a rectangular string table is easy to index but awkward to rearrange. In the final lecture of this group we introduce an array of pointers to strings, which stores only addresses and changes the cost picture entirely.
Frequently Asked Questions
How do I sort an array of strings in C?
Compare rows with strcmp and swap their contents with a temporary buffer and memcpy, using a selection or bubble sort.
What does strcmp return?
A negative value, zero, or a positive value depending on whether the first string is smaller, equal, or larger than the second.
Why can I not swap two rows with the equals sign?
Rows are arrays, and arrays cannot be assigned, so the bytes must be copied.
Why does an uppercase word sort before a lowercase one?
In ASCII, uppercase letter codes are smaller than lowercase letter codes.
Is selection sort good for strings?
It limits the number of swaps, which helps when each swap copies whole rows, but it still needs quadratic comparisons.
Is there a cheaper way to sort strings in C?
Yes. Sort an array of pointers to the strings so a swap exchanges two addresses instead of whole rows.
Free C Programming Course, Keep Going
Next in this free embedded C course: arrays of pointers to strings and why they change the memory picture.

2 Comments