C qsort() vs C++ sort()

CC++Server Side ProgrammingProgramming

Here we will see what are the differences between qsort() in C, and sort() in C++.

The C provides qsort() function, that can be used for sorting an array. The function arguments and syntax is like below.

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

This function takes the base address of that array, the number of elements of that array. Size of each item in the array, and a comparator function.

The C++ provides sort() function. This is present inside C++ STL. The arguments and syntax is like below.

void sort(T first, T last, Compare c);

Here the order of repeated elements is not guaranteed to be preserved. For that purpose, we can use the stable_sort provided by the C++ STL.

The differences between qsort() and sort()

qsort() in Csort() in C++
It uses quicksort algorithm.It uses introsort. This is hybrid sorting algorithm. Here different implementations use different algorithm. The GNU C++ STL uses three-part hybrid sorting. Introsort, Quicksort and Insertion Sort.
The C standard does not talk about the complexities of this sorting algorithm.In this case the complexity is O(n logn) in worst case in C++11 sort(). Some previous version sort() takes O(n2) in worst case, and in average case, they took O(nlogn).
Running time of this sort is larger than sort()The running time is lesser than qsort().
qsort() is not flexible for different kinds of data.sort() is flexible. This can sort C arrays, C++ vectors, C++ deques, and some other containers also.
This sort is not more type safed. It uses unsafe void pointers to access the data.This sorting technique is more safe. It does not require any unsafe void pointer for accessing the data.
Updated on 30-Jul-2019 22:30:26