Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to sort structs by multiple variables in C?

I have to write a function that sorts structs in an array. the struct is:

#define MAX_USERNAME_LENGTH 16

typedef struct{
 char username[MAX_USERNAME_LENGTH];
 unsigned int rides;
 unsigned int rank;
} driver;

The program load the data from a .txt file and fills an array

driver driver_list[256]

I have to sort driver_list by ranks AND number of rides. So if my file contains

//user rides rank
frank209 3 6
john76 7 6
harry99 2 2
bob77 5 2

Output must show:

john76 7 6
frank209 3 6
bob77 5 2
harry99 2 2

There's a way to do that? I've tried selection sort with 2 nested for, but in output i see the list sorted only by rank OR rides. Thanks for help

like image 857
Salvatore Maruccio Avatar asked Dec 14 '25 13:12

Salvatore Maruccio


1 Answers

Use the standard function qsort declared in the header <stdlib.h> and write a user-defined comparison function.

Here you are.

#include <stdio.h>
#include <stdlib.h>

#define MAX_USERNAME_LENGTH 10

typedef struct
{
    char username[MAX_USERNAME_LENGTH];
    unsigned int rides;
    unsigned int rank;
} driver;

int cmp( const void *left, const void *right )
{
    const driver *a = ( const driver *)left;
    const driver *b = ( const driver *)right;

    if ( b->rank < a->rank )
    {
        return -1;
    }
    else if ( a->rank < b->rank )
    {
        return 1;
    }
    else
    {
        return  (  a->rides < b->rides ) - ( b->rides < a->rides );
    }
}


int main(void) 
{
    enum { N = 4 };
    driver driver_list[N] =
    {
        { "frank209", 3, 6 }, 
        { "john76", 7, 6 }, 
        { "harry99", 2, 2 }, 
        { "bob77", 5, 2 }   
    };

    qsort( driver_list, N, sizeof( driver ), cmp );

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%s, %u, %u\n", 
                driver_list[i].username, driver_list[i].rides, driver_list[i].rank );
    }

    return 0;
}

The program output is

john76, 7, 6
frank209, 3, 6
bob77, 5, 2
harry99, 2, 2
like image 92
Vlad from Moscow Avatar answered Dec 16 '25 04:12

Vlad from Moscow