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)
In Worst case Quicksort recursion Depth requires Stack space of O(n). Why it doesn’t
Share
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 requiresO(log n)additional stack space. If you want to, you can make itO(1)stack space andO(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.