qsort : qsort « stdlib.h « C Tutorial






ItemValue
Header filestdlib.h
Declarationvoid qsort(void *buf, size_t num, size_t size, int (*compare) (const void *, const void *));
Functionsorts the array *buf using a Quicksort.
ParameterThe number of elements in the array is specified by num, and the size (in bytes) of each element is described by size.


The function pointed to by compare is used to compare two elements of the array.

The form of the compare function must be as follows:

int func_name(const void *arg1, const void *arg2);

It must return values as described here:

ComparisonValue Returned
arg1 < arg2< 0
arg1 == arg20
arg1 > arg2> zero


The array is sorted into ascending order with the lowest address containing the lowest element.

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

  int num[10] = {
    1, 3, 6, 5, 8, 7, 9, 6, 2, 0
  };

  int comp(const void *, const void *);

  int main(void)
  {
    int i;

    printf("Original array: ");
    for(i=0; i<10; i++) printf("%d ", num[i]);

    qsort(num, 10, sizeof(int), comp);

    printf("Sorted array: ");
    for(i=0; i<10; i++) printf("%d ", num[i]);

    return 0;
  }

  /* compare the integers */
  int comp(const void *i, const void *j)
  {
    return *(int *)i - *(int *)j;
  }
Original array: 1 3 6 5 8 7 9 6 2 0 Sorted array: 0 1 2 3 5 6 6 7 8 9








23.23.qsort
23.23.1.qsort