(算法)Partition方法求数组第k大的数

如题,下面直接贴出代码:

#include <iostream>

using namespace std;

int Partition(int* A,int left,int right){
    int key=A[left];
    while(left<right){
        while(left<right && A[right]>=key)
            right--;
        if(left<right)  A[left]=A[right];

        while(left<right && A[left]<=key)
            left++;
        if(left<right)  A[right]=A[left];
    }
    A[left]=key;
    return left;
}

int findKthNum(int* A,int left,int right,int k){
    int index=Partition(A,left,right);
    if(index+1==k)
        return A[index];
    else if(index+1<k)
        findKthNum(A,index+1,right,k);
    else
        findKthNum(A,left,index-1,k);
}

int main()
{
    int A[]={2,3,5,1,6,7,4};
    int len=sizeof(A)/sizeof(A[0]);

    cout << findKthNum(A,0,len-1,7) << endl;
    return 0;
}

  

    原文作者:AndyJee
    原文地址: https://www.cnblogs.com/AndyJee/p/4722220.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞