7

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?

Christophe
  • 68,716
  • 7
  • 72
  • 138
coderodde
  • 1,269
  • 4
  • 17
  • 34
  • Possible duplicate of [Can we overload malloc()?](http://stackoverflow.com/questions/16270891/can-we-overload-malloc). Also have a look at: [How does sbrk() work in C++?](http://stackoverflow.com/questions/2076532/how-does-sbrk-work-in-c) – πάντα ῥεῖ May 30 '15 at 17:33

1 Answers1

7

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}; }
}
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • Have a upvote for saying _"cplusplus.com is notoriously bad"_. I'm out of votes today. – πάντα ῥεῖ May 30 '15 at 17:41
  • @πάνταῥεῖ oh wow - I didn't even know it was possible to run out of upvotes; you must be more generous than me! Cheers. – Tony Delroy May 30 '15 at 17:43
  • You're running out of votes simply. It doesn't matter if you up- or downvote. I've given downvotes mostly today. Had one left now. It recovers with deleted questions or so. I don't know the exact mechanism. – πάντα ῥεῖ May 30 '15 at 17:44