function

qsort

<cstdlib>
void qsort ( void * base, size_t num, size_t size,
             int ( * compar ) ( const void *, const void * ) );
Sort elements of array
Sorts the num elements of the array pointed by base, each element size bytes long, using the compar function to determine the order.

The sorting algorithm used by this function compares pairs of values by calling the specified compar function with two pointers to elements of the array.

The function does not return any value, but modifies the content of the array pointed by base reordering its elements to the newly sorted order.

Parameters

base
Pointer to the first element of the array to be sorted.
num
Number of elements in the array pointed by base.
size_t is an unsigned integral type.
size
Size in bytes of each element in the array.
size_t is an unsigned integral type.
compar
Function that compares two elements.
This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:

int compar ( const void * elem1, const void * elem2 );

Taking a pointer to two pointers as arguments (both type-casted to const void*). The function should compare the data pointed by both: if they match in ranking, the function shall return zero; if elem1 goes before elem2, it shall return a negative value; and if it goes after, a positive value.

Return Value

(none)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* qsort example */
#include <stdio.h>
#include <stdlib.h>

int values[] = { 40, 10, 100, 90, 20, 25 };

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

int main ()
{
  int n;
  qsort (values, 6, sizeof(int), compare);
  for (n=0; n<6; n++)
     printf ("%d ",values[n]);
  return 0;
}


Output:

10 20 25 40 90 100

See also