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:

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;
}

Output
1 2 3 4 5