2

Methods like sort_by on std::slice::MutableSliceAllocating or sort_by on collections::vec::Vec are documented to "allocate approximately 2 * n, where n is the length". I don't think that good C++ std::sort implementations allocate (on the heap) and yet they accomplish the same O(n log n) complexity. Although, the Rust sort methods are stable unlike the C++ std::sort.

Why do the Rust sort methods allocate? To me, it doesn't fit the "zero cost abstraction" bill advertised here.

kmky
  • 783
  • 6
  • 17
  • 2
    The `sort_by` you reference is stable, so you should compare it with cpp's [stable sort](http://en.cppreference.com/w/cpp/algorithm/stable_sort), which does allocate memory to achieve a lower complexity. – aochagavia Oct 07 '14 at 13:03
  • 1
    @aochagavia, Oh, I didn't know that (and didn't bother to check). Is there an unstable sort function in the Rust standard library then? – kmky Oct 07 '14 at 13:11
  • I don't know :/... I wouldn't be surprised if there is no standard unstable sort, because the language hasn't reached 1.0. Maybe you could submit a PR! – aochagavia Oct 07 '14 at 13:51

2 Answers2

8

I realise this is an old post, but I found it on google and the popular answer is wrong. It is in fact possible to perform a stable in-place sort using O(1) (not even log) memory and worst-case O(nlogn) time. See for example GrailSort or WikiSort.

terpstra
  • 153
  • 1
  • 5
7

As stated in the comment, this is a stable sort, which requires O(n) space to execute. The best O(n log n) stable sort, mergesort, requires about ½n temporary items. (I'm not familiar with Rust, so I don't know why it needs four times that.)

Stable sort can be achieved in O(log n) space, but only by mergesort variant that takes O(n log² n) time.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836