C Standard Libraries C++

qsort()

Declaration

void qsort( const void* kvpArray,
            size_t qNumberOfElements,
            size_t qElementSizeInBytes,
            int (*pfnCompareFn) ( const void *, const void *));

Description

Sorts the elements of an array using the quicksort algorithm. THe first argument "kvpArray" is a pointer to the beginning of the array to be sorted. The value "qNumberOfElements" is the number of elements in the array. The value "qElementSizeInBytes" is the size of each element of the array. Finally, the function pointer, "pfnCompareFn," is the comparison function for comparing two elements of the array. The comparison function returns an int that is less than 0 if the first argument is smaller, 0 if the arguments are equal, and an int that is greater than zero if the the first argument is larger than the second.

Example

#include <iostream>
#include <cstdlib>

int MyCompare(const void* kvpFirst, const void* kvpSecond) {
    int iFirst      = *((int*)(kvpFirst));
    int iSecond     = *((int*)(kvpSecond));
    if (iFirst < iSecond) {
        return -1;
    } else if (iFirst == iSecond) {
        return 0;
    } else {
        return 1;
    }
}

int main() {
    using namespace std;

    int iaArray[9] = {19, 9, 16, 13, 3, 15, 7, 1, 6};
    // Sort the array
    qsort(iaArray, 9, sizeof(int), MyCompare);
    // Output the elements of the sorted array in order
    for (int iIndex = 0; iIndex < 9; ++iIndex) {
        cout << "  " << iaArray[iIndex];
    }
    cout << endl;

    return 0;
}

Output

qsort() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.