What is the qsort() function in C?

The qsort() is a C library function that uses a quick sort algorithm to sort an array. Here is how it is declared in C:

svg viewer

A void pointer is a pointer that can point to any datatype.

The most interesting part of the syntax above is the comparator function. It is called by qsort(), multiple times, to compare two elements. Since the comparator function is user-defined, it can be used to define the logic for comparing elements of any datatype (i.e. structs).

Consider the declaration of comparator below:

int comparator(const void* p1, const void* p2);

The function returns an integer which based on the following criteria:

svg viewer

Example

Consider the code snippet below, which sorts an array in ascending order:

#include <stdlib.h> // needed to use qsort()
int arr[] = {20, 15, 36, -8, 2, 7};
int comparator (const void * p1, const void * p2)
{
return (*(int*)p1 - *(int*)p2);
}
// driver code
int main ()
{
printf("The unsorted array is: \n");
for(int i = 0; i < 6; i++)
{
printf("%d ", arr[i]);
}
qsort(arr, 6, sizeof(int), comparator);
printf("\nThe sorted array is: \n");
for(int i = 0; i < 6; i++)
{
printf("%d ", arr[i]);
}
}

Explanation

  • Lines 5-7: The comparator function takes two void pointers, p1 and p2, as arguments and returns their difference; this is how qsort() determines which element is smaller, or larger, than the other. Note how the pointers are dereferenced in line 7 – more information on dereferencing C pointers can be found here.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved