1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

void print_int_array(int const* array, int size) {
    printf("[");
    for(int i = 0; i < size; i++) {
        printf("%d, ", array[i]);
    }
    printf("]\n");
}

// sorts the array *however* you want to sort it
// this function defines the ordering by defining the order
// of any two elements
int compare_integers(const void* a_left, const void* a_right) {
    // impossible: type(a_left) == int
    // you can do this in one line
    // but doing it over multiple can reduce errors
    const int* a_left_int = a_left;
    const int* a_right_int = a_right;
    int left_int = *a_left_int;
    int right_int = *a_right_int;
    printf("Comparing %d to %d\n", left_int, right_int);

    // returning 1 for left_int < right_int
    //  and     -1 "   "        > "
    // means it sorts in reverse order
    if (left_int < right_int) {
        return 1;
    }
    if (left_int == right_int) {
        return 0;
    }
    assert(left_int > right_int);
    return -1;
}

int main(int argc, char* argv[]) {
    int array [5] = { 5, 2, 3, 1, 4 }; // unsorted array
    print_int_array(array, 5);

    qsort(array, 5, sizeof(array[0]), compare_integers);
    print_int_array(array, 5);

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.