Data structure - three-way division (quick sort optimization)

d8c27d0acd1a422aa5e196d3d08ce561.png

I encountered a problem when flashing Leetcode. I ran it with ordinary quick queue and found that there was a problem.

099021bb94dd4135998075128b463e14.png

 Ordinary Hoare or other quick sorting does not seem to directly solve this problem. When a number appears repeatedly, the efficiency of using ordinary quick sorting is actually not that high. Therefore, this is also one of the shortcomings of ordinary quick queuing.

2f04f5466f3d4bbbb8f457e15e04d46e.png

Therefore, when an element appears multiple times, three-way division can be used to optimize quick sorting.

70a65998131c415db9d3344fadb29066.png

Think about it, why does cur not ++ when arr[cur] > key?

This is because we only know that the value at the cur position is larger than the key, but right does not know whether it is larger or smaller than the key, so we do not use cur++, and right-- is because after the exchange, we already know that it must be larger than the key. .​ 

The source code is as follows:

void QuickSork(int arr[],int left,int right)
{
    if(left >= right)
        return;
    
    int begin = left;
    int end = right;

    int cur = left+1;
    int key = arr[left];
    while(cur <= right)
    {
        if(arr[cur] < key)
        {
            swap(arr[left],arr[cur]);
            cur++;
            left++;
        }else if(arr[cur] > key)
        {
            swap(arr[cur],arr[right]);
            --right;
        }else 
        {
            ++cur;
        }
    }

    QuickSork(arr,begin,left-1);
    QuickSork(arr,right+1,end);

}

 

 

 

Guess you like

Origin blog.csdn.net/m0_72165281/article/details/133924257