qsort - C stdlib.h

C examples for stdlib.h:qsort

Type

function

From


<cstdlib>
<stdlib.h>

Description

Sort elements of array using quick sort algorithm

Prototype

void qsort (void* base,
            size_t num,
            size_t size,
            int (*compare)(const void*,const void*));

Parameters

Parameter Description
base Pointer to the array to be sorted.
num Number of elements in the array.
size Size in bytes of each element in the array.
compare Pointer to a function that compares two elements.

compare function has the following prototype.

int compare (const void* p1, const void* p2);

The above function should return the following value:

return valuemeaning
<0p1 goes before p2
0p1 is equivalent to p2
>0p1 goes after p2

A general compare function may look like:

int compareMyType (const void * a, const void * b)
{
  if ( *(MyType*)a <  *(MyType*)b ) return -1;
  if ( *(MyType*)a == *(MyType*)b ) return 0;
  if ( *(MyType*)a >  *(MyType*)b ) return 1;
}

Return Value

none

Demo Code


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

int values[] = { 4, 1, 10, 9, 2, 25, -1, -2, -10 };

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

int main ()/*from   w ww . j  av a2  s.c om*/
{
  int n;

  qsort (values, 6, sizeof(int), compare);

  for (n=0; n<6; n++)
     printf ("%d ",values[n]);
  return 0;
}

Related Tutorials