0

Here I am again...

The question that I have is this: How do I sort an array of structures by two criteria?

One element of the array looks like this:

struct record{
              char name[32];
              double value;};

The goal would be to sort the array by name and if the name is the same, by value.

For example, let's say the array is:

A 1
B 13
B 1
B 2
C 3
C 1

The result of sorting should be:

A 1
B 1
B 2
B 13
C 1
C 3

My code looks sort of like this:

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

struct record {
    char name[32];
    double value;
};

struct record structs[32];

int function_comparing_values(const void *a, const void *b)
{...
}

int function_comparing_names(const void *a, const void *b)
{...

if (returnvalue==0)
function_comparing_values;                   //THIS IS THE KEY PART RIGHT HERE
else                                         // AND IT'S NOT CORRECT.            
return returnvalue;
}

void function_printing_array(struct record *array, size_t len)
{...
}

void sort_structs_example(void)
{

   {some functions to fill the array}


    print_struct_array(structs, structs_len);

    puts("*** Struct sorting (name)...");

    qsort(structs, structs_len, sizeof(struct record), function_comparing_names);

    print_struct_array(structs, structs_len);
}

int main(){
    sort_structs_example();    return 0;}

If you'd like I could upload the entire code, but I thought that it

would be more readable this way.

Edited by The 42nd: n/a

2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by Narue
0

You've got the right idea, just make sure the details are solid:

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

struct record {
    char name[32];
    double value;
};

int compare(const void *a, const void *b)
{
    const struct record *pa = a;
    const struct record *pb = b;
    
    int diff = strcmp(pa->name, pb->name);
    
    if (diff == 0) {
        if (pa->value < pb->value)
            diff = -1;
        else if (pa->value > pb->value)
            diff = +1;
        else
            diff = 0;
    }
    
    return diff;
}

int main(void)
{
    struct record records[] = {
        {"A", 1},
        {"B", 13},
        {"B", 1},
        {"B", 2},
        {"C", 3},
        {"C", 1}
    };
    int size = 6;
    int i;
    
    qsort(records, size, sizeof(*records), compare);
    
    for (i = 0; i < 6; i++)
        printf("%s %f\n", records[i].name, records[i].value);
    
    return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.