CodeBlanks Logo Icon CodeBlanks

qsort

  • C course
  • Intermediate
  • Lesson 26/116
  • 5 min

Learn to sort with qsort using function pointers.

The qsort function

qsort is the standard library's generic sort function. It works regardless of array type; it takes the comparison via a function pointer.

Signature: qsort(arr, n, sizeof(int), cmp);. Parameters are: array start, element count, element size and the comparator function. The comparator takes two const void * parameters and returns int. It returns negative, zero or positive; this decides the sort direction. qsort needs <stdlib.h>.

The comparator function

The qsort comparator takes two const void * parameters and returns int. Negative means first is smaller; positive means first is larger; zero means equal.

Example: int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }. Here the void * parameters are first cast to int *, then dereferenced. The subtraction gives negative/zero/positive; that's what qsort expects. The comparator decides the sort direction; reversing the subtraction gives descending order.

Practice Sort an array with qsort

Declare int arr[5] = {5, 2, 8, 1, 9};. Write int cmp(const void *a, const void *b) returning *(int *)a - *(int *)b. Sort with qsort(arr, 5, sizeof(int), cmp);. Print with printf("%d ", arr[i]) in a for loop, then printf("\n"). Include <stdlib.h>.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>

// Write the cmp comparator
// Sort the array with qsort
// Print with a for loop

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>

int cmp(const void *a, const void *b) {
    return *(int *)a - *(int *)b;
}

int main(void) {
    int arr[5] = {5, 2, 8, 1, 9};
    qsort(arr, 5, sizeof(int), cmp);
    for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
    printf("\n");
    return 0;
}

Expected output

1 2 5 8 9

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the qsort call

Question
int arr[5] = {5, 2, 8, 1, 9};
____(arr, 5, sizeof(int), cmp);
Answer
int arr[5] = {5, 2, 8, 1, 9};
qsort(arr, 5, sizeof(int), cmp);

Explanation: qsort is the generic sort function.

2 Match the qsort parameters

Term Meaning
arr Array start
5 Element count
sizeof(int) Element size
cmp Comparator

3 What should the qsort comparator return?

  • Only 0 or 1
  • A pointer
  • Boolean
  • Negative, 0 or positive Correct answer

Explanation: The comparator returns negative, 0 or positive.

All lessons in Intermediate