Easy Tutorial
❮ C Function Vsprintf C Nested Switch ❯

C Library Function - qsort()

C Standard Library - <stdlib.h>

Description

The C library function void qsort(void base, size_t nitems, size_t size, int (compar)(const void , const void)) sorts an array.

Declaration

Below is the declaration for the qsort() function.

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

Parameters

Return Value

This function does not return any value.

Example

The following example demonstrates the use of the qsort() function.

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

int values[] = { 88, 56, 100, 2, 25 };

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

int main()
{
   int n;

   printf("List before sorting:\n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

   qsort(values, 5, sizeof(int), cmpfunc);

   printf("\nList after sorting:\n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

  return(0);
}

Let's compile and run the above program, which will produce the following result:

List before sorting:
88 56 100 2 25 
List after sorting:
2 25 56 88 100

C Standard Library - <stdlib.h>

❮ C Function Vsprintf C Nested Switch ❯