How to sort a key-value struct first by value, then by key in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Define the key-value structure
typedef struct {
    char name[32]; // Key (using a fixed-size buffer for safety)
    int score;     // Value
} Record;

/**
 * Comparison function for qsort.
 * Primary sort: Ascending by value (score).
 * Secondary sort: Ascending alphabetically by key (name) as a tie-breaker.
 */
int compareRecords(const void* a, const void* b) {
    const Record* recA = (const Record*)a;
    const Record* recB = (const Record*)b;

    // 1. Compare by value (score)
    if (recA->score != recB->score) {
        return (recA->score > recB->score) - (recA->score < recB->score);
    }

    // 2. Secondary sort (tie-breaker): Compare by key (name) alphabetically
    return strcmp(recA->name, recB->name);
}

int main(void) {
    // Initialize the array with the requested values
    Record records[] = {
        {"Luna", 85},
        {"Sofia", 92},
        {"Charlie", 96},
        {"Bella", 92},
        {"Brock", 80},
        {"Jolie", 96},
        {"Bob", 92},
        {"Eve", 92}
    };

    size_t num_records = sizeof(records) / sizeof(records[0]);

    // Sort the array using standard library qsort
    qsort(records, num_records, sizeof(Record), compareRecords);

    // Print the sorted results
    printf("Sorted by value, then by key:\n");
    for (size_t i = 0; i < num_records; i++) {
        printf("%s: %d\n", records[i].name, records[i].score);
    }

    return 0;
}


/*
run:

Sorted by value, then by key:
Brock: 80
Luna: 85
Bella: 92
Bob: 92
Eve: 92
Sofia: 92
Charlie: 96
Jolie: 96

*/

 



answered Oct 23 by avibootz
...