AcWing 838. 堆排序
原题链接
简单
作者:
autumn_0
,
2025-01-04 21:57:38
,
所有人可见
,
阅读 2
import java.util.Scanner;
public class Main{
public static int N = 100010;
public static int[] h = new int[N];
public static int size;
public static void swap(int x, int y){
int temp = h[x];
h[x] = h[y];
h[y] = temp;
}
public static void down(int u){
int t = u;
if(u * 2 <= size && h[u * 2] < h[t]) t = u * 2;
if(u * 2 + 1 <= size && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
if(u != t){
swap(u, t);
down(t);
}
}
public static void up(int u){
while(u != 0 && h[u] < h[u / 2]){
swap(u, u / 2);
up(u / 2);
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
size = n;
for(int i = 1; i <= n; i ++ ) h[i] = sc.nextInt();
for(int i = n / 2; i > 0; i -- ) down(i);
for(int i = 1; i <= m; i ++ ){
System.out.print(h[1] + " ");
h[1] = h[size -- ];
down(1);
}
}
}