寻找第K大


`class Finder {
public:

int getIndex(vector<int>&a,int low,int high){
    int temp=a[low];
    while(low<high)
    {
        while(low<high && a[high]<=temp)
            high--;
        
        a[low]=a[high];
        while(low<high &&a[low]>temp)
            low++;
        a[high]=a[low];
    }
    a[low]=temp;
    return low;
}




void quicksort(vector<int>&a,int low,int high){
    if(low<high)
    {
        int index=getIndex(a,low,high);
        quicksort(a,low,index-1);
        quicksort(a,index+1,high);
    }
}




int findKth(vector<int>  a, int n, int K) {
    quicksort( a,0,n-1);
    int c=a[K-1];
    return c;
}

};

`
快速排序——就是不断地把第一个数换到中间,找到中间的Index,左边的找比第一个数大的,右边找比第一个数小的,与之进行交换值,必须先找右边的小值,这个原因一定要记住。顺序是不能换的。因为最开始的那个值可能比较大,比左边的那些数大。

posted on 2020-11-18 23:51  timeliar  阅读(53)  评论(0)    收藏  举报