qsort() Comparator Function
The most important part of the qsort() is the comparator function that is passed as a parameter to the qsort() function. The comparator function takes two pointers as arguments that are type casted to const void* and it contains the logic to compare two elements to get the desired order i.e the order in which we want to sort the elements (ascending, descending or any other).
Declaration of Comparator
Function
returnType comparatorName(const void* ptr1, const void* ptr2);
Here, ptr1 and ptr2 are the pointer to the elements to be compared.
The comparator function should have the same signature as above and should return the following values:
- Less than zero (<0): If the element pointed by
ptr1
should be positioned before the element pointed byp2
. - Zero (0): If the element pointed by
p1
is equal to the element pointed byp2
. - Greater than zero (>0): If the element pointed by
p1
should be positioned after the element pointed byp2
.
Note: We can use
qsort()
to sort arrays of any data type, integers, strings and complex structures, by customizing the comparison function accordingly.
qsort() Function in C
The qsort()
function in C is a predefined function in the stdlib.h
library that is used to sort an array of items in ascending order or descending order. It stands for “quick sort,” as it implements the quicksort algorithm for sorting which is one of the fastest and most efficient algorithm to sort elements of an array.