C library function – qsort()

CodingTute

Updated on:

qsort function in C

The qsort() function in C is available in stdlib.h library. As the name indicates, qsort() function internally uses quick sort algorithm and is used to sort array.

Syntax:

void qsort (void *arr, size_t arrSize, size_t elementSize, int (*comparator)(const void *,const void *));
  • arr : pointer to the first index of the array.
  • arrSize : size of the array.
  • elementSize : size of the one element in the array.
  • comparator : function that compares two elements of the array.

The comparator function accepts two pointers as arguments and compares the values pointed by the pointers and returns an integer value based on the comparison.

  • The return value <0 when the first argument pointed value is smaller than second argument pointed value.
  • The return value is >0 when the first argument pointed value is greater than the second argument pointed value.
  • The return value is =0 when the first argument pointed value is equivalent to the second argument pointed value.

Example

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

int arr[] = { 21, 36, 54, 98, 66, 124};

int comparator (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int main () {
   int i;
   printf("Array before sorting : \n");
   for( i = 0 ; i < 6; i++ ) {
      printf("%d ", arr[i]);
   }
   qsort(arr, 6, sizeof(int), comparator );
   printf("\nArray after sorting : \n");
   for( i = 0 ; i < 6; i++ ) {   
      printf("%d ", arr[i]);
   }
   return(0);
}

Output:

Array before sorting :
21 36 54 98 66 124
Array after sorting :
21 36 54 66 98 124