Quicksort slower than Mergesort?

后端 未结 15 1178
名媛妹妹
名媛妹妹 2021-02-07 02:01

I was working on implementing a quicksort yesterday, and then I ran it, expecting a faster runtime than the Mergesort (which I had also implemented). I ran the two, and while th

15条回答
  •  旧巷少年郎
    2021-02-07 02:37

    This is consistent with the analysis of the algorithms. Merge-sort is guaranteed O(nlogn) for any input and for every runtime. Quicksort is best-case O(nlogn) and average case O(nlogn), but worst-case O(n^2), so the average execution will be in between O(nlogn) and O(n^2).

    Quicksort is the best general case algorithm because it has low overhead, so it has good speed for values of n up to about 10000 or so and still good runtime for arbitrarily astronomical values of n. Merge-sort has the unfortunate overhead of writing a stack frame, required by every recursive call. Thus, for low values of n it has an atrociously high c in RT = cnlogn and it is not the preferred general sorting method.

    Edit: Software Monkey pointed out a contradiction: Quicksort averages O(nlogn) for random input, but O(n^2) worst case. So it actually is somewhat bound by the entropy of your data -- or you could choose the pivot randomly. I might still be off a bit though.

提交回复
热议问题