#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int n,m;
int a[N],sz;
void down(int u)//当以1为起始下标,那么一个x的节点左孩子为2*x,右孩子为2*x+1,以0为起始,则是2*x+1和2*x+2,很显然1的时候更好
{
int t=u;
if(u*2<=sz && a[u*2]<a[u]) t=u*2;
if(u*2+1<=sz && a[u*2+1]<a[t]) t=u*2+1;
if(t!=u)
{
swap(a[t],a[u]);
down(t);
}
}
int main()
{
scanf("%d%d",&n,&m);
while(n--)
{
int x;
scanf("%d",&x);
a[++sz]=x;
}
//以1起始,sz/2就是第一个非叶子节点,因为sz是最后一个节点,因为sz/2是向下取整,所以无论是左孩子还是右孩子,都一样
for(int i=sz/2;i>=1;i--)
{
down(i);
}
while(m--)
{
printf("%d ",a[1]);
swap(a[1],a[sz--]);
down(1);
}
return 0;
}
时间复杂度分析