Random selection algorithm to find the Kth largest number

Quick queue application

Ideas

  • The K-th largest number is required, so use partitions sorted from largest to smallest

  • In findK, first partition produces a result, and then compares the relative size of K and the position (pos-left+1) to continue left divide and conquer/right divide and conquer

  • For the case of K>M in the findK function, left needs to be changed, and the value of K needs to be adjusted for the current recursive position of left

    • Description
      • M is the divide and conquer point, which is pos+1-left (because left and pos+1 are relative to 0)
      • K is also relative to left, so it needs to be updated continuously
    0 left M(=pos+1-left) K
    To 0 position 0 left M+left/pos+1
    Position left 0 M
    • M (relative to 0 is pos+1) should be used as the new left point
    • 则newK=K-M=K-pos-1+left
    • FindK(arr, pos+1 , right , KM ) is the distance relative to 0 in bold, and the distance relative to the current left in italics

Code

#include <stdio.h>

int partition(int arr[],int left,int right){
    
    //注意是第K大,所以从大到小
    int temp=arr[left];
    while(left<right){
    
    
        while(arr[right]<=temp&&left<right) right--;
        arr[left]=arr[right];//注意要在这里就解决,在最后right会改变
        while(arr[left]>temp&&left<right) left++;
        arr[right]=arr[left];
    }
    arr[left]=temp;
    //在此处左侧的都比temp小,右侧的都比temp大
    return left;//需要返回下标作为下一次quicksort的位置,类似mid
}

int findK(int arr[],int left,int right,int K){
    
    
    if(left<=right){
    
    
        int pos=partition(arr,left,right);
        int M=pos-left+1;//从left起第M大的数
        if(K==M)
            return arr[pos];
        else if(K<M)
            return findK(arr,left,pos-1,K);
        else
            return findK(arr,pos+1,right,K-M);//注意转化为K-M=K-pos+left-1(相对pos+1来说就是K-left,仍为最初始第K大数)
    }
    return 0;
}

int main(){
    
    
    int n=0,K=0;
    scanf("%d%d",&n,&K);
    int arr[1000005]={
    
    0};
    for(int i=0;i<n;i++)
        scanf("%d",&arr[i]);
    int res=findK(arr,0,n-1,K);
    printf("%d\n",res);
}

Guess you like

Origin blog.csdn.net/Cindy_00/article/details/108567108