StackOverflowException when perform Quicksort with ordered list

后端 未结 1 1317
野的像风
野的像风 2021-01-28 17:59

I\'m implementing Quick sort algorithm in C#. Implementation as follow:

    /// 
    /// Perform Sort
    /// 
    //         


        
相关标签:
1条回答
  • 2021-01-28 18:13

    Without inspecting your code...

    The naive quicksort has best-case complexity of O(n log n), but worst case of only O(n). The worst case is (you guessed it) when the list is sorted. On a sorted collection, the pivot chosen as the leftmost element will separate a sublist into an empty list and everything else, and then recurse into a sublist that is just one element less than the original (the pivot). Thus, your stack depth needs to be at least the same as the number of elements you're sorting. So if you have a largish collection, a StackOverflowException is not unexpected.

    The only fix, really, is not using the naive quicksort. You can detect if the collection is sorted or nearly sorted and switch to another algorithm; or you can use another method of choosing a median that will decrease the likelihood of the degenerate case (for example, while sorted collections are commonly possible, such collections that will trigger a degenerate case when you select the middle element instead of the left one as pivot are much rarer). Cases where you expect near-sorted collections to be common can also benefit from three-value-median method of pivot selection; many more variations are possible.

    EDIT: If you have a bug in your code, that is a pretty good source of errors too :P An empty list is sorted by default - nothing to do, move along... Same with one-element lists. So if you just have a check if right is before or at left and return early without changing it, your bug should go away. It's as simple as

    if (right < left) return;
    
    0 讨论(0)
提交回复
热议问题