Quicksort Algorithm (Cormen) gives Stackoverflow

家住魔仙堡 提交于 2019-12-02 08:21:01

Yes, this pivot scheme is not right choice for sorted array. It causes very unbalanced partition, leads to O(N^2) complexity and very deep recursion level, as you noticed.
There are some approaches to improve this behavior. For example, you can use random index for pivot like pivotIdx = start + rand() % (end-start+1);, or choose median-of-three method (median of the first, last and middle elements in index range).

P.S. An option to avoid stack overflow - call recursion for shorter segment at first, then for longer one.

https://en.wikipedia.org/wiki/Quicksort#Choice_of_pivot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!