What is qsort() in C?
qsort() is a standard C library function that uses the QuickSort algorithm to sort arrays. It is a part of the stdlib.h header file in C. Below is the declaration of the qsort() function:
void qsort (void* base, size_t num, size_t size, int(* comparator)(const void*, const void*));
The qsort() function has no return value. It sorts the array pointed by base by reordering the elements of the array.
Parameters of the qsort() function
base: Pointer to the first element of the arraynum: Number of elements in the arraysize: Size (in bytes) of each element of the arraycomparator: Function that compares two elements of the array
Comparator
The comparator function is declared as follows:
int comparator (const void * num1, const void * num2);
The comparator function returns an integer by comparing num1 and num2 as follows:
- Greater than 0: if value pointed by
num1is higher than the value pointed bynum2 - Equal to 0: if value pointed by
num1is equivalent to the value pointed bynum2 - Less than 0: if value pointed by
num1is lower than the value pointed bynum2
Code
Consider the code snippet below, which uses qsort() to sort an array:
#include <stdio.h>#include <stdlib.h>int comparator (const void * num1, const void * num2) {return (*(int*)num1 - *(int*)num2);}void printArray(int arr[], int arrSize) {for (int i=0; i<arrSize; i++) {printf("%d ", arr[i]);}}int main() {int arr[] = {12, 56, 2, 9, 1};int arrSize = 5;printf("Array before sorting: \n");printArray(arr, arrSize);qsort(arr, arrSize, sizeof(int), comparator);printf("\nArray after sorting: \n");printArray(arr, arrSize);return 0;}
Explanation
- Lines 4-6: The
comparatorfunction returns the difference ofnum1andnum2passed to it as parameters. This return value determines the location ofnum1with respect tonum2in the sorted array. - Lines 8-12: The
printArrayfunction takes an array and its size as parameters and prints the elements of the array. - Lines 22:
qsort()is used to sort arrayarrthat is created in line 16.qsort()sortsarrin ascending order using the comparator function declared in line 4.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved