Why choose a random pivot in quicksort

感情迁移 提交于 2019-12-06 16:36:43

Your algorithm suffers O(n2) if you choose average of min value and max value as pivot when the list contains the following elements:

1, 3, 7, 15, 31, 63, ..., 2n-1

You could find that for each pass of your algorithm, the right part always has only 1 element.

Three things:

  1. You can get the max and min in one pass of the list, so actually we add 1*O(n) for each pass. However...

  2. The average of max and min doesn't guarantee O(nlog(n)), since the average of the maximum and minimum is not necessarily the median value. If you have an already sorted list (1,10,100,1000,10000), this would actually give an O(n^2) solution, which is really bad for an already sorted list (and fairly likely to happen).

  3. Choosing a random pivot is statistically likely to give you something close to the median. Take a random number from a list, 50% of the time this number is in the middle 50% of the list, meaning in the worst case it has 75% of the list to one side and 25% on the other. Obviously performance is even better when we chose closer to the true median.

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