![]() |
VOOZH | about |
In C, qsort() is used for sorting an array in desired order. But to provide compatibility to different data types, it additionally requires a comparator function to determine the order of how to arrange the elements.
Let's take a look at an example:
1 2 3 4 5
Explanation: In the above code, the comparator function is used to guide the qsort() to sort the array in ascending order.
There are some rules for defining a comparator function for qsort():
Comparator Function Signature:
The comparator function shall take two arguments and contains logic to decide their relative order in the sorted output. According to the convention, comparator function should have the following signature:
int comp(const void* p1, const void* p2);
Parameters:
Return Value:
The comparator function should only return the following values:
The below examples demonstrates the use of comparator function with qsort() to sort the array in different orders:
5 4 3 2 1
As we can see, we have to first convert the void pointer to the relevant type to work on actual data.
for geeks geeks to welcome