Why does QuickSort use O(log(n)) extra space?

后端 未结 5 895
刺人心
刺人心 2020-12-13 17:39

I have implemented the below quicksort algorithm. Online I\'ve read that it has a space requirement of O(log(n)). Why is this the case? I\'m not creating any extra data stru

5条回答
  •  时光取名叫无心
    2020-12-13 18:05

    If you read further in the Wikipedia article, you will find a more thorough discussion of space complexity. In particular, they write:

    Quicksort with in-place and unstable partitioning uses only constant additional space before making any recursive call. Quicksort must store a constant amount of information for each nested recursive call. Since the best case makes at most O(log n) nested recursive calls, it uses O(log n) space. However, without Sedgewick's trick to limit the recursive calls, in the worst case quicksort could make O(n) nested recursive calls and need O(n) auxiliary space.

    Practically speaking, O(log n) memory is nothing. For instance, if you were to sort 1 billion ints, storing them would require 4 GB, but the stack would only require about 30 stack frames, at something like 40 bytes, so about 1200 Bytes in total.

提交回复
热议问题