Comparator Function of qsort() in C (original) (raw)
Last Updated : 10 Jan, 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:
C `
#include <stdio.h> #include <stdlib.h>
int comp(const void* a,const void* b) { return (int)a - (int)b; }
int main() { int arr[5] = {1, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]);
qsort(arr, n, sizeof(int), comp);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
`
**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
C++ `
#include <stdio.h> #include <stdlib.h>
// Comparator to sort in descending order int comp(const void* a,const void* b) { return (int)b - (int)a; }
int main() { int arr[5] = {1, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]);
qsort(arr, n, sizeof(int), comp);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
`
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
C++ `
#include <stdio.h> #include <stdlib.h> #include <string.h>
// Comparator function for strings int comp(const void *a, const void b) { return strcmp((const char **)a, *(const char **)b); }
int main() { const char *arr[] = {"welcome", "to", "geeks", "for", "geeks"}; int n = sizeof(arr) / sizeof(arr[0]);
// Sort array of strings
qsort(arr, n, sizeof(const char *), comp);
for (int i = 0; i < n; i++)
printf("%s ", arr[i]);
return 0;
}
`
Output
for geeks geeks to welcome