[Solved] How to priority sort characters?


So, you want to sort an array of custom objects, like this:

typedef struct {
    char c;  // a character
    int i;   // a number
} pair;

Then you can apply a standard function qsort() with a custom compare function like this:

int compare(const void *a, const void *b) {
    pair *p1 = (pair*) a;
    pair *p2 = (pair*) b;
    if (p1->c == p2->c) return p1->i - p2->i;
    if (p1->c == 'C' || p1->c == 'G' && p2->c == 'A') return -1;
    return 1;
}

So that this testing code with your test data will print C,1 C,8 G,2 G,5 A,4 A,7 A,10

int main() {
    pair input[] = {{'A', 10}, {'A', 7}, {'G', 5},
                    {'C', 8}, {'A', 4}, {'C', 1}, {'G', 2}};
    qsort(input, 7, sizeof(pair), compare);
    pair *cur = input;
    for (int i=0; i<7; ++i, ++cur) {
        printf("%c,%d ", cur->c, cur->i);
    }
    printf("\n");
}

How to transform arbitrary input into array of structures, is an exercise.

12

solved How to priority sort characters?