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 > b
1int 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 safer
2 return (*(int *)a - *(int *)b);
3}
4
// Comparator for descending order: the same idea with the operands swapped
5int compare_desc(const void *a, const void *b) {
// b - a is positive when a is smaller, so larger values come first
6 return (*(int *)b - *(int *)a);
7}
8
// The array to sort
9int nums[] = {5, 2, 8, 1, 9};
// Arguments: array, element count, element size, comparator
10qsort(nums, 5, sizeof(int), compare_asc);
// Prints Asc: 1 2 5 8 9 followed by a newline
11printf("Asc: ");
12for (int i = 0; i < 5; i++) printf("%d ", nums[i]);
13printf("\n");
14
// Sorts the same array again, this time in descending order
15qsort(nums, 5, sizeof(int), compare_desc);
// Prints Desc: 9 8 5 2 1
16printf("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

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

More C examples at level 5

← C typing practice