Quicksort Algorithm (Cormen) gives Stackoverflow

后端 未结 1 1048
太阳男子
太阳男子 2020-12-21 23:50

i implemented the Quick Sort Algorithm which given pseudo code in Introduction to Algorithms (Cormen, 3rd Edition) 7.1

When i tried algorithm with small sized arrays

相关标签:
1条回答
  • 2020-12-22 00:06

    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

    0 讨论(0)
提交回复
热议问题