median of three values strategy

前端 未结 8 1611
粉色の甜心
粉色の甜心 2020-11-29 23:08

What is the median of three strategy to select the pivot value in quick sort?

I am reading it on the web, but I couldn\'t figure it out what exactly it is? And also

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 23:48

    The common/vanilla quicksort selects as a pivot the rightmost element. This has the consequence that it exhibits pathological performance O(N²) for a number of cases. In particular the sorted and the reverse sorted collections. In both cases the rightmost element is the worst possible element to select as a pivot. The pivot is ideally thought to me in the middle of the partitioning. The partitioning is supposed to split the data with the pivot into two sections, a low and a high section. Low section being lower than the pivot, the high section being higher.

    Median-of-three pivot selection:

    • select leftmost, middle and rightmost element
    • order them to the left partition, pivot and right partition. Use the pivot in the same fashion as regular quicksort.

    The common pathologies O(N²) of sorted / reverse sorted inputs are mitigated by this. It is still easy to create pathological inputs to median-of-three. But it is a constructed and malicious use. Not a natural ordering.

    Randomized pivot:

    • select a random pivot. Use this as a regular pivot element.

    If random, this does not exhibit pathological O(N²) behavior. The random pivot is usually quite likely computationally intensive for a generic sort and as such undesirable. And if it's not random (i.e. srand(0); , rand(), predictable and vulnerable to the same O(N²) exploit as above.

    Note that the random pivot does not benefit from selecting more than one element. Mainly because the effect of the median is already intrinsic, and a random value is more computationally intensive than the ordering of two elements.

提交回复
热议问题