qsort() function in C++

In this guide, you will learn what is qsort() function is in C++ programming and how to use it with an example.

1. qsort() Function Overview

The qsort() function, part of the C standard library <cstdlib> in C++, provides a way to sort an array. It implements the QuickSort algorithm and can be used to sort arrays of any data type, provided a comparison function is supplied.


void qsort(void* base, size_t nitems, size_t size, int (*compar)(const void*, const void*));


- base: A pointer to the first element of the array to be sorted.

- nitems: The number of elements in the array.

- size: The size in bytes of each element in the array.

- compar: A function pointer to the comparison function which determines the order of sorting.

2. Source Code Example

#include <iostream>
#include <cstdlib>

// Comparison function for ascending sort
int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);

int main() {
    int values[] = {40, 10, 100, 90, 20, 25};

    // Number of elements in the array
    int n = sizeof(values) / sizeof(values[0]);

    std::cout << "Before sorting:" << std::endl;
    for(int i = 0; i < n; i++)
        std::cout << values[i] << " ";
    std::cout << std::endl;

    // Using qsort to sort the array
    qsort(values, n, sizeof(int), compare);

    std::cout << "After sorting:" << std::endl;
    for(int i = 0; i < n; i++)
        std::cout << values[i] << " ";
    std::cout << std::endl;

    return 0;


Before sorting:
40 10 100 90 20 25
After sorting:
10 20 25 40 90 100

3. Explanation

1. We define a comparison function compare(). It is designed for sorting in ascending order. This function takes two void pointers as arguments, which point to the elements being compared. Inside the function, these pointers are cast to the appropriate data type (int* in this case) and used for comparison.

2. In the main() function, we have an integer array values that we wish to sort.

3. We print the array before sorting.

4. We use the qsort() function, providing the necessary parameters like the base address of the array, the number of items, the size of each item, and the comparison function.

5. After sorting, we print the sorted array.

Note: The qsort() function can sort arrays of any data type, not just integers. However, a suitable comparison function must be provided for the specific data type.