VOOZH about

URL: https://www.geeksforgeeks.org/c/comparator-function-of-qsort-in-c/

⇱ Comparator Function of qsort() in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Comparator Function of qsort() in C

Last Updated : 23 Jul, 2025

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:


Output
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.

Rules for Defining Comparator Function

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:

  • p1, p2: Pointer to the elements to be compared.

Return Value:

The comparator function should only return the following values:

  • Less than zero (<0): If the first argument should be placed before the second argument.
  • Zero (0): If both arguments are equal.
  • Greater than zero (>0): If the first argument should be placed after the second argument.

Examples of Comparator

The below examples demonstrates the use of comparator function with qsort() to sort the array in different orders:

Sort Array of Integers in Descending Order


Output
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.

Sort Array of Strings Lexicographically


Output
for geeks geeks to welcome 




Comment