//第k大数,第k小的数--前k大数,k小的数-----------------------------------------------------------------------
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
//每次选择第一个元素作为划分点,比它小放左边,比它大放右边
int partitionV2(int *a,int low,int high)
{
int key=a[low];
int i=low,j=high;
while(i<j)
{
while(i<j&&a[j]>=key)j--;
a[i]=a[j];
while(i<j&&a[i]<=key)i++;
a[j]=a[i];
}
a[i]=key;
return i;
}
//寻找第k大数
int find_K_max(int *a,int n,int k)
{
/*
8 3
1 5 3 4 2 6 8 7
11 6
78934 234 65 32 543 354 567 3412 3 547 423
11 5
11 6 78934 234 65 32 543 354 567 3412 3
*/
int low=0,high=n-1;
while(low<=high)
{
int index=partitionV2(a,low,high);
if(index==n-k)
{
return a[index];
}
else if(index<n-k)
{
low=index+1;
}
else
{
high=index-1;
}
}
}
//寻找第k小数
int find_K_min(int *a,int n,int k)
{
/*
8 3
1 5 3 4 2 6 8 7
11 6
78934 234 65 32 543 354 567 3412 3 547 423
11 5
11 6 78934 234 65 32 543 354 567 3412 3
*/
int low=0,high=n-1;
while(low<=high)
{
int index=partitionV2(a,low,high);
if(index==k-1)
{
return a[index];
}
else if(index<k-1)
{
low=index+1;
}
else
{
high=index-1;
}
}
}
int main()
{
int n,k;
int a[100];
while(cin>>n>>k)
{
vector<int> mv(n);
for(int i=0;i<n;++i)
{
cin>>a[i];
mv[i]=a[i];
}
cout<<find_K_min(a,n,k)<<endl;
sort(mv.begin(),mv.end());
cout<<mv[k-1]<<endl;
}
return 0;
}
快排划分思想的应用-求第k大数或者第k小的数(求前k大数或者前k小的数)
最新推荐文章于 2021-02-23 20:11:17 发布