Quick Sorting Structures – Solution

The task for this month’s Exercise is to extract a structure member from a void pointer for use in the quick-sort compare() function. This isn’t a solution you can readily find on the Interwebs.

I must have hammered away at various solutions for hours when originally confronted with this problem. I tried every possible combination of asterisk/parentheses weirdo expression I could muster. Eventually, stepping away from the keyboard — and avoiding the temptation to drink heavily — yielded a clean solution.

The first thing you must realize is that it’s weirdly complicated to construct a single return statement to handle the job. Rather than keep trying, I decided to first convert the void pointers into compatible structures. Here is the format:

one = *(struct film *)a;

Variable one is a film structure. It’s assigned to the passed pointer *a, first argument in the compare() function, which must be typecast to a film structure pointer. Once this conversion is made, struct variable one is available for comparing the year member values, as shown in my full solution here:

2022_12-Exercise.c

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

struct film {
    char title[32];
    int year;
};

int compare(const void *a, const void *b)
{
    struct film one,two;

    one = *(struct film *)a;
    two = *(struct film *)b;

    return( one.year - two.year );
}

int main()
{
    const int size = 9;
    struct film bond[size] = {
        { "Casino Royale", 2006 },
        { "Dr. No", 1962 },
        { "GoldenEye", 1995 },
        { "Goldfinger", 1964 },
        { "Moonraker", 1979 },
        { "Octopussy", 1983 },
        { "Skyfall", 2012 },
        { "Spectre", 2015 },
        { "Thunderball", 1965 }
    };
    int x;

    /* sort the list by year */
    qsort(bond,size,sizeof(struct film),compare);

    /* output results */
    for( x=0; x<size; x++ )
        printf("%d, %s\n",
                bond[x].year,
                bond[x].title
              );

    return(0);
}

Even when I tried to compress the two statements in the compare() function, eliminating variables one and two and setting the conversions into the return statement, the program refused to compile. Only by declaring two film structures, converting the data in two statements, and then comparing the year members, did my solution work.

It would thrill me to see another solution, something that uses a different approach. As I wrote in the original Exercise post, most programmers tend to copy-paste their compare() functions. Yet power exists in this function, part of the quick-sort process. Let me know if you also met with success.

Leave a Reply