快排划分思想的应用-求第k大数或者第k小的数(求前k大数或者前k小的数)

//第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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值