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 a data field (quicksort)

&pagelevel(4)&pagelevel

Parameters  void *field

Pointer to the first element of the array to be sorted.

size_t n

Number of elements to be sorted.

size_t elsize

Size of an element, in bytes.

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

Pointer to a function that compares two elements and returns a whole number as its result. This result is interpreted as follows:

Definition

#include <stdlib.h>

void qsort(void *field, size_t n, size_t elsize, int (*comp)(const void *, const void *);

qsort sorts n elements of an array field using the quicksort algorithm. Each array element is elsize bytes in length.
In order to be able to sort the field, qsort requires a function comp (to be provided by the user), which compares two elements with each other.


Parameter

void *feld

Pointer to the first element of the array to be sorted.

size_t n

Number of elements to be sorted.

size_t elsize

Size of an element, in bytes.

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

Pointer to a function that compares two elements and returns a whole number as its result. This result is interpreted as follows:

< 0

= 0

> 0

argument1 is less than argument2

argument1 and argument2 are equal

argument1 is greater than argument2

< 0

argument1 is less than argument2

= 0

argument1 and argument2 are equal

> 0

argument1 is greater than argument2

The function has two parameters, i.e. two pointers to the type of the array elements.

The function may be defined something like this:

Example 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);
}

Example 2

/*compares two integer values */
int compare(const void *a, const void *b)
{
  return  ( *((const int *) a) - *((const int *) b) );
}

Note

Array elements that are determined to be equal by the comparison function are retained in the same order.

Example

The following program sorts a number field and outputs it on the standard output.

#include <stdio.h>
#include <stdlib.h>
int comp   (const void *s, const void *t)
{
    return  ( *((const int *) s) - *((const int *) t) );
}
int main(void)
{
  int j;
  static int array[] = {4,7,2,1,54,9,2,3,1,23};
  qsort (array, 10, sizeof(int), comp);
  for (j=0; j<10; j++)
     printf("%d\n", array[j]);
  return 0;
}

See also

bsearch