Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quicksort recursion depth Stack space of O(n) doesnot cause stackoverflow?

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)

like image 376
Rahul Kumar Dubey Avatar asked Mar 07 '26 06:03

Rahul Kumar Dubey


1 Answers

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.

like image 196
Steve Jessop Avatar answered Mar 09 '26 12:03

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!