算法设计--查找无序数组中第K大的数字

时间:2022-12-30 15:36:46

    给出一个数组,要求查找出这个数组中按顺序排第K大的数字。

思路:利用快速排序的思想,把数组中的元素分治,并计算中间值的位置,如果是K,则这个数就是第K大的数字,如果比K小,那么再次利用快速排序分治中值 以后的数据,如果比K大,则排序前面的数字,直到找到K的位置。

下面给出C++实现的代码:

#include <cstdlib>
#include <iostream>

using namespace std;

int partition(int data[],int first,int last)  //¿ìËÙÅÅÐòµÄ·Öλ 
{
int pivot=data[first];
while(first<last)
{
while(first<last&&data[last]>pivot) 
last--;  data[first]=data[last];
while(first<last&&data[first]<pivot)
first++; data[last]=data[first];                
}
data[first]=pivot;
return first;    
}

int findKth(int data[],int first,int last,int k)
{
int kth;
if(first==last)  kth=data[first];
else
{
int pivot=data[first];    //Ïȸø¼Ç¼ÏÂÀ´ 
int splitPoint=partition(data,first,last);  //ÕâÊÇÿһ´Î·Ö¸îµÄµãλ 
if(k<splitPoint)
kth=findKth(data,first,splitPoint-1,k);
else 
if(k>splitPoint) 
kth=findKth(data,splitPoint+1,last,k);
else 
kth=pivot;   
}     
return kth;
}
int main(int argc, char *argv[])
{
    int a[11]={-1,11,17,18,5,7,14,9,6,27,21};
    //ÕýÈ·µÄ˳ÐòÊÇ£º5,6,7,9,11,14,17,18,21,27 
    int t=findKth(a,1,10,6);
    cout<<t<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}