Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::sort check if a vector is already sorted?

I believe that the C++ standard for std::sort does not guarantee O(n) performance on a list that's already sorted. But still, I'm wondering whether to your knowledge any implementations of the STL (GCC, MSVC, etc) make the std::is_sorted check before executing the sort algorithm?

Asked another way, what performance can one expect (without guarantees, of course) from running std::sort on a sorted container?

Side note: I posted some benchmarks for GCC 4.5 with C++0x enabled on my blog. Here's the results:

Comparison of std::sort and std::is_sorted

like image 671
Alan Turing Avatar asked Jul 04 '11 04:07

Alan Turing


3 Answers

Implementations are free to use any efficient sorting algorithm they want so this is highly implementation dependant

However I have seen a performance comparison of libstdc++ as used on linux and against libc++ the new C++ library developed by Apple/LLVM. Both these libraries are very efficient on sorted or reverse sorted data (much faster than on a random list) with the new library being considerable faster then the old and recognizing many more patterns.

To be certain you should consider doing your own benchmarks.

like image 121
Eelke Avatar answered Oct 17 '22 03:10

Eelke


No. Also, it's not logical to have is_sorted() called for any STL implementation. Since, is_sorted() is available already as a stand-alone. And many users may not want to waste execution cycles unnecessarily to call that function when they already know that their container is not sorted.

STL also should be following the C++ philosophy: "pay per use".

like image 44
iammilind Avatar answered Oct 17 '22 03:10

iammilind


Wow! Did you have optimizations all the way cranked up?

Here's the results of your code on my platform (note the values on the vertical axis).

like image 11
Howard Hinnant Avatar answered Oct 17 '22 04:10

Howard Hinnant