What is the complexity of std::sort()
in the C++ Standard Library? Which sort is applied? Is there any rule of applying any particular sorting algorithm there?
The std::sort is a sorting function that uses the Introsort algorithm and have the complexity of O(N log(N)) where N= std::distance(first, last) since C++11 and the order of equal elements is not guaranteed to be preserved[3].
The new C++11 standard requires that the complexity of sort to be O(Nlog(N)) in the worst case. Previous versions of C++ such as C++03 allow possible worst case scenario of O(N^2). Only average complexity was required to be O(N log N). 3.
In C++, the standard library provides a pre-defined and ready to use function sort() to carry out this sorting operation.
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort().
Before C++11:
std::sort
must have average case linearithmic (n log n) time complexity. Any algorithm may be used so long as that time complexity requirement is met. There is no worst case time complexity requirement.
If you want a guaranteed worst case time complexity function, use std::stable_sort
, which has quasilinear worst case time complexity (n log^2 n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With