Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Profiling stable_sort

This page tells that whenever there is not enough memory, stable_sort reduces to an in-place algorithm with running time O(n(log n)(log n)):

Complexity

If enough extra memory is available, linearithmic in the distance between first and last: Performs up to N*log2(N) element comparisons (where N is this distance), and up to that many element moves. Otherwise, polyloglinear in that distance: Performs up to N*log22(N) element comparisons, and up to that many element swaps.

I want to profile it against another in-place algorithm with the same running time, so my question reduces to: how can I simulate a "lack of memory" so that the slower algorithm is performed in stable_sort?

like image 451
coderodde Avatar asked May 30 '15 17:05

coderodde


People also ask

What is the difference between sort and Stable_sort?

stable_sort() is used to sort the elements in the range [first, last) in ascending order. It is like std::sort, but stable_sort() keeps the relative order of elements with equivalent values. It comes under the <algorithm> header file.

Is std :: sort stable C++?

Yes, it's as you said, and this is not a concept unique to C++. Stable sorts preserve the physical order of semantically equivalent values. std::sort : The order of equal elements is not guaranteed to be preserved.

Is C++ sort stable sort?

C++ Algorithm stable_sort() function is used to sort the elements in the range [first, last) into ascending order like sort but keeps the order of equivalent elements. The elements are compared using operator < for the first version, and comp for the second version.


1 Answers

cplusplus.com is notoriously bad... looking at cppreference.com's description here

This function attempts to allocate a temporary buffer equal in size to the sequence to be sorted, typically by calling std::get_temporary_buffer. If the allocation fails, the less efficient algorithm is chosen.

get_temporary_buffer is:

template< class T >
std::pair< T*, std::ptrdiff_t > get_temporary_buffer( std::ptrdiff_t count )

So, while it will technically be underfined behaviour to specialise it for your own class in the std namespace, you're presumably not doing this for production code and in practice it's extremely likely to work reliably and would let you intercept the memory request and return failure.

namespace std
{
    template <>
    std::pair<My_Class*, std::ptrdiff_t>
    get_temporary_buffer(std::ptrdiff_t)
    { return {0, 0}; }
}
like image 160
Tony Delroy Avatar answered Oct 17 '22 21:10

Tony Delroy