C++ cstdlib qsort()

January 4, 2025 India, Himachal Pradesh, Ghumarwin 14

Description

qsort() is a standard library C++ cstdlib qsort() (from the cstdlib header) that implements the quicksort algorithm. It allows sorting an array of elements using a user-defined comparison function.


 


Syntax:


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


Parameters:


 


base: Pointer to the first element of the array.


 


num: Number of elements in the array.


 


size: Size of each element in bytes.


 


compar: Pointer to the comparison function, which determines the order of elements.


 


Usage Example:


#include <cstdlib>


#include <iostream>


 


int compare(const void* a, const void* b) {


    return (*(int*)a - *(int*)b);


}


 


int main() {


    int arr[] = {3, 1, 4, 1, 5, 9};


    size_t size = sizeof(arr) / sizeof(arr[0]);


 


    qsort(arr, size, sizeof(int), compare);


 


    for (int i = 0; i < size; i++) {


        std::cout << arr[i] << " ";


    }


    return 0;


}


Key Points:fv


 


qsort() is useful for sorting arrays of any type by customizing the comparison function.


 


Use caution with typecasting in the comparison function.


Share by email Share on Facebook Share on Twitter Share on Google+ Share on LinkedIn Pin on Pinterest