#include <stdlib.h>void qsort(void *buf, size_t num, size_t size,           int (*compare) (const void *, const void *));

The qsort( ) function sorts the array pointed to by buf using a Quicksort (developed by C.A.R. Hoare). The Quicksort is generally considered the best general-purpose sorting algorithm. The number of elements in the array is specified by num, and the size (in bytes) of each element is described by size.

The function pointed to by compare is used to compare two elements of the array. The form of the compare function must be as follows:

int func_name(const void *arg1, const void *arg2);

It must return values as described here:

The array is sorted into ascending order with the lowest address containing the lowest element.

A related function is bsearch( ).

Programming Tip 

When using qsort( ), if you want to sort an array in descending order (that is, high to low), simply reverse the conditions used by the comparison function. That is, have the comparison function return the following values:


Value Returned

arg1 is less than arg2

Less than zero

arg1 is equal to arg2


arg1 is greater than arg2

Greater than zero

Also, if you want to use the bsearch( ) function on an array that is sorted in descending order, you will need to use a reversed comparison function.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net