median of three values strategy

前端 未结 8 1614
粉色の甜心
粉色の甜心 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条回答
  •  Happy的楠姐
    2020-11-29 23:53

    Think faster... C example....

    int medianThree(int a, int b, int c) {
        if ((a > b) != (a > c)) 
            return a;
        else if ((b > a) != (b > c)) 
            return b;
        else
            return c;
    }
    

    This uses XOR like operator. So you would read:

    • Is a greater than exclusively one of the others? return a
    • Is b greater than exclusively one of the others? return b
    • If none of above: return c

    The median approach is faster because it would lead to more evenly partitioning in array, since the partitioning is based on the pivot value.

    In the worst case scenario with a random pick or a fixed pick you would partition every array into an array containing just the pivot and another array with the rest, leading to an O(n²) complexity.

    Using the median approach you make sure that won't happen, but instead you are introducing an overhead for calculating the median.

    EDIT:

    Benchmarks results show XOR is 32 times faster than Bigger even though I optimized Bigger a little:

    You need to recall that XOR is actually a very basic operator of the CPU's Arithmetic Logic Unit (ALU), then although in C it may seen a bit hacky, under the hood it is compiling to the very efficient XOR assembly operator.

提交回复
热议问题