Median of 3 partitioning

前端 未结 1 1339
再見小時候
再見小時候 2021-01-20 15:37

I found the following code for finding a pivot for quicksort using median of first, last and middle element:

int middle = ( low + high ) / 2;
if( a[ middle ]         


        
相关标签:
1条回答
  • 2021-01-20 16:11

    The reason is that the algorithm does not only find the median, it also sorts the low, middle and high elements. After the three permutations you know that a[middle]<=a[high]. So you need only to partition the elements before high, because a[high] is greater or equal to pivot.

    Let's look at an example: low=0, middle=4 and high=8. Your array is like this:

    lowerOrEqualToPivot X X X pivot X X X greaterOrEqualToPivot
    

    If you swap middle with high, you need to partition the 8 elements between brackets :

    [ lowerOrEqualToPivot X X X greaterOrEqualToPivot X X X ] pivot
    

    If you swap middle with high-1, you need to split only 7 elements:

    [ lowerOrEqualToPivot X X X X X X ] pivot greaterOrEqualToPivot
    

    By the way there is a bug in the first line:

    int middle = ( low + high ) / 2; //Wrong
    int middle = ( low + high ) >>> 1; //Correct
    

    The reason is that if (low + high) is greater than Integer.MAX_VALUE you will have an overflow and middle will be a negative number. The second line will always give you a positive result.

    0 讨论(0)
提交回复
热议问题