What are Sort Structure Arrays in C- Embedded C Training For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Structure and Union · Lecture 26

Sort Structure Arrays in C

Learn how to sort an array of structures by name, date or number using one clean comparator per key. A hands-on lesson from our free C programming course and free embedded C course.

If you are following this free C programming course, you already know how to define a structure and keep many of them in an array. The next real-world question is always the same: how do I put those records in order? Firmware images by build date, sensor logs by name, tasks by priority. In this lecture of our free embedded C course you will learn to sort an array of structures in C by any field, and to avoid the copy-paste trap of writing one almost identical sort function for every field.

What You Will Learn

  • Why one sort function per field becomes a maintenance problem
  • How to compare strings, numbers and nested date structures
  • The negative / zero / positive contract used by every C comparator
  • How to write one sort routine that accepts the comparison as a function pointer
  • How to sort ascending and descending without touching the sort loop
  • Common mistakes when sorting structures in embedded C programs

Prerequisites

You should be comfortable with arrays of structures, nested structures, strcmp() and the basic idea of a pointer to a function. If function pointers feel shaky, revisit the Pointers chapter of this free C tutorial first, then come back.

Why Sorting Structures Needs a Plan

Sorting an int array is easy because the elements compare with <. A structure has several members, and each one may need a different kind of comparison. A name is compared with strcmp(). A size is compared as a number. A date is a structure inside the structure, so it has to be compared piece by piece: year first, then month, then day.

The beginner approach is to write sort_by_name(), sort_by_date(), sort_by_size() and so on. Each function contains the same two loops and the same three-line swap, and only the if condition differs. When you later find a bug in the swap, or want to switch to a faster algorithm, you must fix every copy. In a firmware project that is exactly how inconsistent behaviour sneaks in.

The cleaner idea: separate how to walk and swap from how to decide which record goes first. The walking and swapping is written once. The decision is a tiny function you pass in.

One sort routine, many comparators
cmp_name()cmp_built()cmp_size_desc()
↓ chosen by caller ↓
sort_images(list, n, cmp)
↓ loops + swap written once ↓
sorted array of struct fw_image

The Record We Will Sort

We will model a table of firmware images stored on an embedded board. Each image has a name, the date it was built and its size in kilobytes. The date is its own structure, so this example also revises nested structures.

struct date {
    int year;
    int month;
    int day;
};

struct fw_image {
    char name[16];
    struct date built;
    unsigned int size_kb;
};

The Comparator Contract

Every comparison function in C follows one agreement, the same one used by strcmp() and by the standard qsort() library function:

Return valueMeaningEffect in our sort
Negativefirst record should come before secondno swap
Zerorecords are equal for this keyno swap
Positivefirst record should come after secondswap

Pick one convention and keep it

Some older textbooks return 1 when the first date is the smaller one. That is the reverse of what strcmp() does and confuses everyone who reads the code later. Use the standard contract above everywhere, and your comparators become interchangeable with library functions.

Comparing Dates Inside a Structure

A date is ordered by year, then month, then day. The month matters only when the years are equal, and the day only when both year and month are equal. That “only when everything before it is equal” rule is the heart of every multi-field comparison.

static int cmp_date(const struct date *a, const struct date *b)
{
    if (a->year != b->year)
        return a->year - b->year;
    if (a->month != b->month)
        return a->month - b->month;
    return a->day - b->day;
}
Date comparison: first difference wins
year equal?no → answer from year
month equal?no → answer from month
dayanswer from day (0 if same date)
Watch out: subtracting values is safe here because years, months and days are small. For large unsigned values such as 32-bit timestamps, subtraction can wrap around. Compare with < and > instead, as the size comparator below does.

Writing One Comparator Per Key

Each comparator takes two pointers to records and returns the contract value. Taking pointers avoids copying a whole structure for every comparison, which matters when the structure is large and the CPU is a small microcontroller.

static int cmp_name(const struct fw_image *a, const struct fw_image *b)
{
    return strcmp(a->name, b->name);
}

static int cmp_built(const struct fw_image *a, const struct fw_image *b)
{
    return cmp_date(&a->built, &b->built);
}

static int cmp_size_desc(const struct fw_image *a, const struct fw_image *b)
{
    if (b->size_kb > a->size_kb)
        return 1;
    if (b->size_kb < a->size_kb)
        return -1;
    return 0;
}

Look at cmp_size_desc(). To sort largest first we did not change the sort loop at all. We simply flipped the operands inside the comparator. Ascending versus descending is purely a decision of the comparison function.

The Single Sort Routine

The routine below uses a simple exchange sort: compare element i with every later element and swap when they are out of order. It is easy to read and perfectly fine for the small tables common in embedded code. The only new thing is the last parameter, a pointer to a function that takes two const struct fw_image * and returns an int.

static void sort_images(struct fw_image list[], int n,
                        int (*cmp)(const struct fw_image *, const struct fw_image *))
{
    int i, j;
    struct fw_image tmp;

    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            if (cmp(&list[i], &list[j]) > 0) {
                tmp = list[i];
                list[i] = list[j];
                list[j] = tmp;
            }
        }
    }
}

Notice that tmp = list[i] copies the entire structure, name array and nested date included, in one assignment. Structure assignment is legal in C and copies every member, which is exactly what a swap needs.

Complete Program: Build and Run

Save the following as fw_sort.c. It contains the structures, the comparators, the sort routine and a small printer.

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

#define COUNT 5

struct date { int year; int month; int day; };

struct fw_image {
    char name[16];
    struct date built;
    unsigned int size_kb;
};

static int cmp_name(const struct fw_image *a, const struct fw_image *b)
{ return strcmp(a->name, b->name); }

static int cmp_date(const struct date *a, const struct date *b)
{
    if (a->year != b->year)   return a->year - b->year;
    if (a->month != b->month) return a->month - b->month;
    return a->day - b->day;
}

static int cmp_built(const struct fw_image *a, const struct fw_image *b)
{ return cmp_date(&a->built, &b->built); }

static int cmp_size_desc(const struct fw_image *a, const struct fw_image *b)
{
    if (b->size_kb > a->size_kb) return 1;
    if (b->size_kb < a->size_kb) return -1;
    return 0;
}

static void sort_images(struct fw_image list[], int n,
                        int (*cmp)(const struct fw_image *, const struct fw_image *))
{
    int i, j;
    struct fw_image tmp;
    for (i = 0; i < n - 1; i++)
        for (j = i + 1; j < n; j++)
            if (cmp(&list[i], &list[j]) > 0) {
                tmp = list[i]; list[i] = list[j]; list[j] = tmp;
            }
}

static void show(const char *title, const struct fw_image list[], int n)
{
    int i;
    printf("--- %s ---\n", title);
    for (i = 0; i < n; i++)
        printf("%-10s %04d-%02d-%02d %4u KB\n", list[i].name,
               list[i].built.year, list[i].built.month,
               list[i].built.day, list[i].size_kb);
}

int main(void)
{
    struct fw_image fw[COUNT] = {
        { "bootrom",  { 2025, 11, 3 },  64 },
        { "ble_fw",   { 2026,  2, 18 }, 412 },
        { "app_main", { 2025, 11, 3 },  980 },
        { "dsp_blob", { 2024,  7, 29 }, 256 },
        { "bootldr",  { 2026,  2, 1 },  128 }
    };

    sort_images(fw, COUNT, cmp_name);
    show("by name", fw, COUNT);
    sort_images(fw, COUNT, cmp_built);
    show("by build date", fw, COUNT);
    sort_images(fw, COUNT, cmp_size_desc);
    show("by size, largest first", fw, COUNT);
    return 0;
}

Compile and run it on any Linux machine or in an online compiler:

$ gcc -Wall -Wextra -o fw_sort fw_sort.c
$ ./fw_sort

Expected output:

--- by name ---
app_main   2025-11-03  980 KB
ble_fw     2026-02-18  412 KB
bootldr    2026-02-01  128 KB
bootrom    2025-11-03   64 KB
dsp_blob   2024-07-29  256 KB
--- by build date ---
dsp_blob   2024-07-29  256 KB
bootrom    2025-11-03   64 KB
app_main   2025-11-03  980 KB
bootldr    2026-02-01  128 KB
ble_fw     2026-02-18  412 KB
--- by size, largest first ---
app_main   2025-11-03  980 KB
ble_fw     2026-02-18  412 KB
dsp_blob   2024-07-29  256 KB
bootldr    2026-02-01  128 KB
bootrom    2025-11-03   64 KB

Reading the output

In the build-date listing, bootrom and app_main share the date 2025-11-03. Before this step the list was sorted by name, so app_main sat ahead of bootrom, yet bootrom came out first. This exchange sort is not stable: it does not promise to keep equal records in their old order. If you need a guaranteed tie-breaker, add a second comparison inside the comparator, for example fall back to strcmp() on the name when the dates match.

Real-World Uses in Embedded Programming

Embedded scenarioRecordSort key
Boot loader image tableimage name, version, sizeversion, newest first
Sensor log reviewtimestamp, sensor id, valuetimestamp
Task scheduler tabletask name, priority, periodpriority
BLE scan resultsdevice name, address, RSSIsignal strength, strongest first

Common Mistakes

  • Comparing strings with ==. That compares addresses of two arrays, not their text. Always use strcmp().
  • Forgetting the tie rule in dates. Comparing only the year, or checking month and day without checking that earlier fields are equal, gives wrong results.
  • Swapping only one member. If you swap just the sort key, the rest of the record stays behind and your data is corrupted. Swap the whole structure.
  • Mixing conventions. One comparator returning 1 for “smaller” and another returning 1 for “larger” makes the shared sort routine unpredictable.
  • Looping to n instead of n - 1. The outer loop should stop one element early, otherwise the inner loop starts past the end of the array.

Best Practices and Performance

  • Pass records to comparators by const pointer, never by value.
  • For tables of a few dozen entries, the exchange sort above is fine. For larger data, use the standard qsort() with the same comparator idea.
  • If a structure is large, sort an array of pointers to the records instead of moving the records themselves. Swapping 8-byte pointers is far cheaper than swapping 100-byte structures.
  • Keep comparators free of side effects and printing so they can be reused and tested alone.

Suggested Images for This Lecture

Image ideaALT text
Table of firmware records before and after sortingsort array of structures in C free C programming course example
Flow showing comparator feeding the sort routineC comparator function pointer free embedded C course diagram
Terminal screenshot of the program outputfree C tutorial structure sorting program output in terminal

Key Takeaways

  • Sorting structures means choosing a key and a comparison, then swapping whole records.
  • Use the strcmp-style contract: negative, zero, positive.
  • Dates compare year first, then month, then day, stopping at the first difference.
  • One sort routine plus a function pointer replaces many nearly identical sort functions.
  • Ascending or descending is decided inside the comparator, not the loop.

Conclusion

You have now seen the pattern that real C code uses to order records: a small comparator for each key and a single reusable sort routine. This idea scales from a five-entry boot table on a microcontroller to millions of records on a Linux server. In the next lecture of this free C programming course we will let a structure hold a pointer to another structure of its own kind, the foundation for linked lists, and that is where dynamic data structures in embedded C programming begin.

Frequently Asked Questions

How do I sort an array of structures in C?

Choose the member to sort by, write a comparison function that returns a negative, zero or positive value, and use a sort loop (or qsort()) that swaps whole structures when the comparison says they are out of order.

Can I assign one structure to another in C?

Yes. A plain assignment copies every member, including arrays and nested structures. That is why a three-line swap with a temporary structure works.

Why not compare strings with the == operator?

For character arrays, == compares the addresses of the arrays, which are always different. Use strcmp() to compare the text.

How do I sort in descending order?

Swap the two operands inside the comparator, or negate its result. The sort routine itself does not change.

Is qsort() better than writing my own sort?

For larger arrays, yes. It is tested and efficient, and it uses the same negative/zero/positive comparator idea. On tiny systems without a full C library, a simple hand-written sort is common.

How do I sort by two fields, such as date then name?

Compare the first field. If the result is non-zero, return it. Otherwise return the comparison of the second field.

Is this lecture part of a free embedded C course?

Yes. It belongs to the EmbeddedPathashala free C programming course, which is written for students who want to use C for embedded systems.

Keep Going With the Free C Programming Course

Next up: self referential structures, the building block of linked lists in C.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →