qsort Function

Sort and array of objects.

Include

<stdlib.h>

Prototype

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

Argument

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

Remarks

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.

Example

#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