qsort Function

Sort an array of objects.




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


the array to sort
the number of objects in the array
the size of each object being sorted
the comparison function to be used


The qsort function orders the elements in the base array so that they are in an ascending order, as specified by the function pointed to by compar. The comparison function should take two arguments, and should return an integer value less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.


See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int cmp (int *num1, int *num2)
  if (*num1 < *num2)
    return -1;
  if (*num1 > *num2)
    return 1;
  return 0;

int main (void)
  int array[] = {12, 92, 0, -1, 6, -24, 101};
  size_t arraylen = sizeof(array) / sizeof(int);

  qsort (array, arraylen, sizeof(int), (int (*)(const void *, const void *)) cmp);
  printf("Array elements:\n");
  for (int i=0; i != arraylen; i++) {
    printf("%d%s", array[i], i==arraylen-1 ? "\n" : " ");

Example Output

Array elements:
-24 -1 0 6 12 92 101