nth_element详解

nth_element()是c++的STL库中的函数,作用是将数组中第k小的整数放在区间第k个位置

比如a[6]={2,5,6,4,7,8},使用nth_element(a,a+3,a+6)后,区间中第四个数,也就是a[3],会被放入数组中第四小的数,也就是6( a a a的下标是从0开始的)。

使用一次nth_element()的时间复杂度为 O ( n ) O(n) O(n)

code

#include<bits/stdc++.h>
using namespace std;
int a[6]={2,5,6,4,7,8};
int main()
{
    nth_element(a,a+3,a+6);
    for(int i=0;i<6;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

输出:

5 2 4 6 7 8 

如果a数组不从0开始,则需做一些调整

code

#include<bits/stdc++.h>
using namespace std;
int n,k,b[15];
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
        scanf("%d",&b[i]);
    }
    nth_element(b+1,b+k,b+n+1);
    for(int i=1;i<=n;i++){
        printf("%d ",b[i]);
    }
    printf("\n");
    printf("%d",b[k]);
    return 0;
}

输入:

8 4
7 5 3 8 4 6 2 9

输出:

3 2 4 5 8 6 7 9 
5
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值