问题
In Worst case Quicksort recursion Depth requires Stack space of O(n). Why it doesn't cause a stack overflow for large set in the worst case? (reversed sequence)
回答1:
If you recurse on both sides of the pivot then it does cause stack overflow for sufficiently large data in the worst case. That's why nobody uses a naive QuickSort in production code.
There is a simple change you can make to the algorithm to prevent Omega(n)
worst-case stack use. After each partition, recursively Quicksort the "small half" and then iteratively loop around to do the "big half". This requires O(log n)
additional stack space. If you want to, you can make it O(1)
stack space and O(log n)
additional non-stack space by modifying this again. Push the "big half" onto the end of a pre-allocated array (or other last-in-first-out data structure of your choice), loop around to do the "small half", and when you hit bottom pop the last element off the data structure to do next.
There are further changes you can make to avoid Omega(n^2)
worst-case runtime. But then it's not a naive QuickSort any more, it's a QuickSort-with-median-of-medians-pivot-selection, or an Introsort, or whatever.
回答2:
Then Why it doesnot causes stack overflow for large set of data of order in worst case
It does. Why would you assume that it doesn’t?
(But note that the worst case input for quicksort depends on the pivot you chose. It’s not generally the reversed sequence – and in fact, for a naive choice of pivot another worst-case input is an already sorted sequence, it doesn’t have to be reversed.)
But library implementations of sort algorithms are actually rarely quicksort nowadays, precisely for this reason. For instance, the C++ std::sort uses introsort instead, which is a modified quicksort that will switch to a different sorting algorithm as soon as it recurses too deeply.
回答3:
It could cause a stack overflow in the case of a reversed sequence (the worest case). Because an array could be too large for the internal function stack. (99,000,000 elements, for example) You could just replace recursion with a stack
data structure. You will loop while (stck.empty() == false)
function quicksort(arr[0,1,...n-1])
stack.push(pair(0, n - 1))
while stack not empty
interval = stack.pop()
...
...
stack.push(interval(0, pivot - 1))
stack.push(interval(pivot + 1, n - 1))
来源:https://stackoverflow.com/questions/12970688/quicksort-recursion-depth-stack-space-of-on-doesnot-cause-stackoverflow