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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
void print_ints(int* array_of_ints, size_t num_elements) {
for(int i = 0; i < num_elements; i++) {
printf("%d ", array_of_ints[i]);
}
printf("\n");
}
int compare_fn(const void* a_n1, const void* a_n2) {
int const* a_n1_int = a_n1;
int const* a_n2_int = a_n2;
int n1 = *a_n1_int;
int n2 = *a_n2_int;
log_yellow("compare_fn(%d, %d)\n", n1, n2);
if(n1 < n2) {
return -1;
}
else if(n1 == n2) {
return 0;
}
else {
assert(n1 > n2);
return 1;
}
}
int main(int argc, char* argv[]) {
int array[] = { 2, 1, 3 };
size_t num_elements = 3;
print_ints(array, num_elements);
qsort(array, num_elements, sizeof(array[0]), compare_fn);
print_ints(array, num_elements);
return EXIT_SUCCESS;
}
/*
* The comparison function must return an integer less than, equal to, or greater than
* zero if the first argument is considered to be respectively less than, equal to, or
* greater than the second. If two members compare as equal, their order in the sorted
* array is undefined.
*/
/* 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.