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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
int _compare_int(const void* a1, const void* a2) {
// Implicitly convert address of (anything) to address of an int.
int* a_n1 = a1;
int* a_n2 = a2;
// Get the ints at those addresses.
int n1 = *a_n1;
int n2 = *a_n2;
// Compare the two ints.
if(n1 < n2) {
return -1;
}
else if(n1 == n2) {
return 0;
}
else {
assert(n1 > n2);
return 1;
}
}
/* “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.”
*/
int main(int argc, char* argv[]) {
int numbers[] = { 4, 2, 6, 1, 3, 5, 7 };
size_t num_numbers = sizeof numbers / sizeof numbers[0]; // only with int a[] = {…} !!!
qsort(number, num_numbers, sizeof numbers[0], _compare_int);
for(int i = 0; i < 7; i++) {
assert(numbers[i] == i + 1); // assuming numbers are 1, 2, ..., 6, 7
}
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2024 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.