qsort() Function In C and C++

C Programming language provides the qsort() function in order to sort integers in an array. The array should consist of numbers which can be integers, long integers, or floating-point numbers. The qsort() function also called comparator it is used to compare numbers and sort them properly. In this tutorial, we examine the qsort() function syntax, qsort() function usage, and different sorts of examples like sorting integers, long integers, or floating-point numbers.

qsort() Function Library

The qsort() function is provided via the stdlib.h library or header. So in order to use the qsort() function it should be included like below.

#include <stdlib.h>

qsort() Function Syntax

The syntax of the qsort() function is like below.

void qsort (void* base, size_t num, size_t size, int (*comparator)(const void*,const void*));
  • void* base is the array that contains numbers.
  • size_t num is the size of the item in the array.
  • size_t size is the size of a single item in the provided array.
  • int (*compar)(const void *, const void*) is the comparator function used to compare integers.

Sort Numbers

In the following example we sort numbers or integers those are stored inside the array named values . We create a function to compare numbers and return negative, zero, or positive numbers according to the comparison result which is used by the qsort() function to sort accordingly. First, we print numbers in an unsorted way and then call qsort() with the help of compare() function and print sorted numbers.

#include <stdio.h>
#include <stdlib.h>

int values[] = { 7,2,4,9,0,1,3,8 };

int compare(const void * x, const void * y) {
   return ( *(int*)x - *(int*)y );
}

int main () {
   int n;

   printf("Print Unsorted List \n");
   for( n = 0 ; n < 8; n++ ) {
      printf("%d ", values[n]);
   }

   qsort(values, 8, sizeof(int), compare);

   printf("\nSorted List: \n");
   for( n = 0 ; n < 8; n++ ) {   
      printf("%d ", values[n]);
   }
  
   return(0);
}

Sort Floating Point Numbers

We can also sort floating point numbers easily by using the qsort() function. In the following example, we sort floating point numbers with the help of the compare() function.

#include <stdio.h>
#include <stdlib.h>

int values[] = { 0.7, 0.2, 0.4, 0.9, 0.0, 0.1, 0.3, 0.8 };

int compare(const void * x, const void * y) {
   return ( *(float*)x - *(float*)y );
}

int main () {
   int n;

   printf("Print Unsorted List \n");
   for( n = 0 ; n < 8; n++ ) {
      printf("%f ", values[n]);
   }

   qsort(values, 8, sizeof(float), compare);

   printf("\nSorted List: \n");
   for( n = 0 ; n < 8; n++ ) {   
      printf("%f ", values[n]);
   }
  
   return(0);
}

Leave a Comment