Can you choose any pivot you want in quicksort?

杀马特。学长 韩版系。学妹 提交于 2020-12-11 10:05:50

问题


I recently saw Quick Sort - Computerphile video on Youtube about how quicksort works (on paper) and I have a question. Imagine that we have an array that contains for example "27,6,19,2,15,9,10". In first place I choose 10 as pivot and the array becomes like this: 9,2,6 |10| 27,19,15. Then I choose 6 as pivot for the left unsorted array and it becomes 2 |6| 9 and for the right one I choose 19 as a pivot and the right unsorted array becomes 15 |19| 27. The question is: Can I choose any pivot I want to make my job easier (like I did in this example) or there is something more?

Edit: If I chose 27 as pivot instead of 19 how the array would be?


回答1:


You can choose any value such that no part of the partition will be empty, i.e. not smaller than the smallest nor larger than the largest. (The value needn't be one of an element of the array.)

The more balanced the partition (so the closer to the median), the better. Even though this is never done, the arithmetic mean could do.

A common strategy is the median of three (first, central and last elements).




回答2:


In principle you can take any array element as the pivot; the algorithm will work. In practice, if you pick the smallest or largest element of the array as the pivot, one pass of the Quicksort algorithm will achieve very little. Say you have the numbers from 1 to 100 in random order and choose 1 as the pivot, then you will still have an array with 99 elements to sort. The worst possible case is picking the first array element as the pivot if the array is already sorted.




回答3:


Take a look at this question and answer.

There is a discussion showing that choosing a random pivot is probably the best choice in most scenarios.



来源:https://stackoverflow.com/questions/38854953/can-you-choose-any-pivot-you-want-in-quicksort

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