How does random shuffling in quick sort help in increasing the efficiency of the code?

前端 未结 5 990
忘掉有多难
忘掉有多难 2020-12-28 20:00

I was going through lecture videos by Robert Sedgwick on algorithms, and he explains that random shuffling ensures we don\'t get to encounter the worst case quadratic time s

5条回答
  •  温柔的废话
    2020-12-28 20:10

    It's really an admission that although we often talk about average case complexity, we don't in practice expect every case to turn up with the same probability.

    Sorting an already sorted array is worst case in quicksort, because whenever you pick a pivot, you discover that all the elements get placed on the same side of the pivot, so you don't split into two roughly equal halves at all. And often in practice this already sorted case will turn up more often than other cases.

    Randomly shuffling the data first is a quick way of ensuring that you really do end up with all cases turning up with equal probability, and therefore that this worst case will be as rare as any other case.

    It's worth noting that there are other strategies that deal well with already sorted data, such as choosing the middle element as the pivot.

提交回复
热议问题