Adam Kotvas Adam Kotvas - 6 months ago 45
C Question

Sort a vector of pairs by first element then by second element of the pair in C

If I have a structure POINT in C with coordinates x and y, what is the accepted way to sort it by the first element of the pair and then by second if the firsts are equal? I found many answer on this in C++ but not in C..can you help?


Just use qsort and an appropriate compare function, e.g.

// point type

typedef struct {
    int x;
    int y;
} Point;

// point compare function

int compare_points(const void *p1, const void *p2)
    const Point *pt1 = p1;
    const Point *pt2 = p2;

    // do primary compare on x
    if (pt1->x > pt2->x)
        return 1;
    if (pt1->x < pt2->x)
        return -1;

    // pt1->x == pt2->x - do secondary compare on y...
    if (pt1->y > pt2->y)
        return 1;
    if (pt1->y < pt2->y)
        return -1;

    // pt1 == pt2
    return 0;        

// sort an array of points...

qsort(points, num_points, sizeof(Point), compare_points);