(算法)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;
}

  

posted @ 2015-08-11 20:20  AndyJee  阅读(566)  评论(0编辑  收藏  举报