838. 堆排序
题目链接https://www.acwing.com/problem/content/description/840/
题目:
时间复杂度0(nlogn)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e5+10;
int a[N];
int n,m;
void down(int u){
int t=u;
if(u*2<=n && a[u*2]<a[t]) t=u*2;
if(u*2+1<=n&&a[u*2+1]<a[t]) t=u*2+1;
if(t!=u){
swap(a[t],a[u]);
down(t);
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=n/2;i;i--)
down(i);
while(m--){
printf("%d ",a[1]);
a[1]=a[n--];
down(1);//每次输出小顶堆的头结点后,要更新小顶堆
}
return 0;
}
皮一下,sort大法好
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e5+10;
int a[N];
int n,m;
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1);
for(int i=1;i<=m;i++)
printf("%d ",a[i]);
return 0;
}