Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of std::sort() in the C++ standard library?

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?

like image 919
Hari Chaudhary Avatar asked Dec 19 '10 20:12

Hari Chaudhary


People also ask

What is the time complexity of std::sort ()?

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].

What is the time complexity of built in sort function in C++?

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.

Which library is used for sort in C++?

In C++, the standard library provides a pre-defined and ready to use function sort() to carry out this sorting operation.

What does sort () do in C++?

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().


1 Answers

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).

like image 80
James McNellis Avatar answered Oct 07 '22 21:10

James McNellis