QSORT(C++) C++ Library QSORT(C++) NAME qsort - sorts an array SYNOPSIS #include <iostream> #include <cstdlib> using namespace std; void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); DESCRIPTION The qsort() function sorts an array with nmemb elements of size size. The base argument points to the start of the array. The contents of the array are sorted in ascending order according to a comparison function pointed to by compar, which is called with two arguments that point 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. If two members compare as equal, their order in the sorted array is undefined. RETURN VALUE The qsort() function returns no value. EXAMPLE #include <iostream> #include <string> using namespace std; // for sorting by l_name ( char[] ) int compare ( const void *, const void * ); // for sorting by id ( int ) int compare_int ( const void *, const void * ); // for sorting by earn ( double ) int compare_double ( const void *, const void * ); struct A { char f_name[15]; char l_name[15]; int id; double earn; }; int main (void) { int i = 0; A data[3] = { {"Jone","Smith",345055,65345.34}, {"Mike","Wood",546934,34565.65}, {"Jime","Rones",456098,76543.05} }; qsort ( reinterpret_cast<char*>(data), 3, sizeof(A), compare ); while ( i < 3 ) { cout << data[i].f_name << " " << data[i].l_name << " " << data[i].id << " " << data[i].earn << endl; i++; } cout << endl; qsort ( reinterpret_cast<char*>(data), 3, sizeof( A ), compare_int ); i = 0; while ( i < 3 ) { cout << data[i].f_name << " " << data[i].l_name << " " << data[i].id << " " << data[i].earn << endl; i++; } cout << endl; qsort ( reinterpret_cast<char*>(data), 3, sizeof( A ), compare_double ); i = 0; while ( i < 3 ) { cout << data[i].f_name << " " << data[i].l_name << " " << data[i].id << " " << data[i].earn << endl; i++; } cout << endl; return 0; } int compare (const void *v1, const void *v2) { return (strcmp(((struct A *)v1)->l_name, ((struct A *)v2)->l_name)); } int compare_int (const void *v1, const void *v2) { return ((struct A *)v1)->id - ((struct A *)v2)->id; } int compare_double (const void *v1, const void *v2) { return ((((struct A *)v1)->earn) - (((struct A *)v2)->earn) > 0 ) ? 1 : 0; } Output: Jime Rones 456098 76543.1 Jone Smith 345055 65345.3 Mike Wood 546934 34565.7 Jone Smith 345055 65345.3 Jime Rones 456098 76543.1 Mike Wood 546934 34565.7 Mike Wood 546934 34565.7 Jone Smith 345055 65345.3 Jime Rones 456098 76543.1 CONFORMING TO SVID 3, POSIX, BSD 4.3, ISO 9899 SEE ALSO sort(1) AUTHORS David Metcalfe, Rik Faith, Anatoliy Urbanskiy