Name

qsort - sorts an array

Library

libc.lib

Synopsis

  #include <stdlib.h>
  void qsort (void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void));

Return values

The qsort function returns no value.

Detailed description

The qsort function is a modified partition-exchange sort, or quicksort.

The qsort function sorts an array of nmemb objects, the initial member of which is pointed to by base. The size of each object is specified by size.

The contents of the array base are sorted in ascending order according to a comparison function pointed to by compar, which requires two arguments pointing to the objects being compared.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The algorithm implemented by qsort is not stable, that is, if two members compare as equal, their order in the sorted array is undefined.

The qsort function is an implementation of C.A.R. Hoare’s "quicksort" algorithm, a variant of partition-exchange sorting; in particular, see D.E. Knuth Ns ’s Algorithm Q. Quicksort takes O N lg N average time. This implementation uses median selection to avoid its O N**2 worst-case behavior.


Examples

#include <stdio.h>
#include <stdlib.h>
int sort_function( const void *a, const void *b);
 
int main(void)
{
   int  x;
   int list[5] = {4,2,3,5,1};
   qsort((void *)list, 5, sizeof(list[0]), sort_function);
   for (x = 0; x < 5; x++)
   printf("%d\n", list[x]);
  
   return 0;
}
int sort_function( const void *a, const void *b)
{
 int *p1 = (int *)a;
 int val1 = *p1;
 int *p2 = (int *)b;
 int val2 = *p2;
 int x = -1;
 if(val1  > val2 )
   x=1;
 if(val1  == val2 )
   x=0; 
 
 return x;
}

         

Output

1
2
3
4
5

         

Errors

No errors are defined.

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia

Top