Qsort Comparator in C
Level 5435 keystrokes
Sorts {5, 2, 8, 1, 9} with the standard qsort, first with an ascending comparator and then with a descending one. Each comparator returns a negative, zero or positive value; the program prints Asc: 1 2 5 8 9 and Desc: 9 8 5 2 1.
C code
// qsort comparator for ascending order: negative if a < b, 0 if equal, positive if a > b1int compare_asc(const void *a, const void *b) { // Casts the void pointers to int *, reads both values and subtracts them // Subtraction can overflow for extreme values; (x > y) - (x < y) is safer2 return (*(int *)a - *(int *)b);3}4 // Comparator for descending order: the same idea with the operands swapped5int compare_desc(const void *a, const void *b) { // b - a is positive when a is smaller, so larger values come first6 return (*(int *)b - *(int *)a);7}8 // The array to sort9int nums[] = {5, 2, 8, 1, 9};// Arguments: array, element count, element size, comparator10qsort(nums, 5, sizeof(int), compare_asc);// Prints Asc: 1 2 5 8 9 followed by a newline11printf("Asc: ");12for (int i = 0; i < 5; i++) printf("%d ", nums[i]);13printf("\n");14 // Sorts the same array again, this time in descending order15qsort(nums, 5, sizeof(int), compare_desc);// Prints Desc: 9 8 5 2 116printf("Desc: ");17for (int i = 0; i < 5; i++) printf("%d ", nums[i]);Output
Asc: 1 2 5 8 9 Desc: 9 8 5 2 1
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
(× 19)× 19,× 14;× 14*× 12"× 10_× 4+× 4[× 3]× 3