Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

qsort - sort table of data

&pagelevel(4)&pagelevel

Syntax

#include <stdlib.h>

void qsort (void * base, size_t nel, size_t width, int ( *compar) (const void *, const void *));

Description  The qsort() function is an implementation of the quicksort algorithm. It sorts a table of data

in place. The contents of the table are sorted in ascending order according to the
usersupplied comparison function. base points to the element at the base of the table. nel is the
number of elements in the table. width specifies the size of each element in bytes. compar
is the name of the user-defined comparison function, which is called by qsort() with two
arguments that point to the elements being compared. This function must return an integer
less than, equal to, or greater than zero to indicate if the first argument is to be considered
less than, equal to, or greater than the second.

The comparison function may be defined as follows:

/* Program fragment 1 compares two char values */
int comp(const void *a, const void *b)
{
   if(*((const char *)a) < *((const char *) b) )
      return(-1);
   else if(*((const char *)a) > *((const char *) b ) )
      return(1);
   return(0);
}
/* Program fragment 2 compares two integer values */
int compare(const void *a, const void *b)
{
   return  ( *((const int *) a) - *((const int *) b) );
}

Notes

The comparison function need not compare every byte, so arbitrary data may be contained
in the elements in addition to the values being compared.

Extension
In contrast to XPG4, the order of array members that are considered equal by the
comparison function is not changed. (End)

See also

stdlib.h.