7

I always thought it the space complexity is O(1) but I looked online and it uses different sorting algorithms at different stages which has confused me, what exactly is the space complexity of std::sort and when are they different?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Does this answer your question? [What's the memory complexity of std::sort() and std::sort\_heap()?](https://stackoverflow.com/questions/26286612/whats-the-memory-complexity-of-stdsort-and-stdsort-heap) – Cortex0101 Jun 27 '21 at 15:06

1 Answers1

6

The "space complexity" of std::sort is not defined. However, it is not allowed to dynamically allocate memory (as it is not allowed to throw std::bad_alloc unless your types do when copied/moved). So the only space it could take up is stack space. And its allowed to take up however much an implementation desires.

sort tends to be implemented as some variation of quick-sort, so that tends to be recursively implemented, so it would probably use O(log(n)) calls on average.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • And your implementation would know what the maximum possible number of array elements in the implementation is, so O(log n) is some not very large constant. In that implementation. – gnasher729 Jun 26 '21 at 21:31
  • 1
    @gnasher729: "*And your implementation would know what the maximum possible number of array elements in the implementation is*" No, it wouldn't. `std::sort` works on any random access range, not just standard library containers. – Nicol Bolas Jun 26 '21 at 21:33
  • Yes, but given random-access iterators, calculating the size of the range is cheap. – Marshall Clow Jun 26 '21 at 22:35
  • @MarshallClow: The size is dynamic, and therefore it is not a "constant", large or otherwise, as gnasher suggested. – Nicol Bolas Jun 26 '21 at 23:49