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
#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");
}

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;

    if (left_int < right_int) {
        return -1; // left is less than right
    }
    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.