quicksort stack size

前端 未结 3 1138
广开言路
广开言路 2020-12-10 16:42

Why do we prefer to sort the smaller partition of a file and push the larger one on stack after partitioning for quicksort(non-recursive implementation)? Doing this reduces

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 16:56

    Consider the worst case where you partition in such a way that your partition is 1:n. If you sort small subfile first than you only need to use O(1) space, as you push the large subfile and then pop it back (and then again push the large subfile). But, if you sort large subfile first than you need O(N) space, because you keep pushing 1 element array in the stack.

    Here is a quote from Algorithms by ROBERT SEDGEWICK (he was the one who wrote paper on this) :

    For Quicksort, the combination of end- recursion removal and a policy of processing the smaller of the two subfiles first turns out to ensure that the stack need only contain room for about, lg N entries, since each entry on the stack after the top one must represent a subfile less than half the size of the previous entry.

提交回复
热议问题