Now we can note module of HeapSort.
The problem.Problem in AcWing
The problem is to print the minimal k number, it’s easy to change the output when we need. The Time Complexity is O(nlogn).
And the Code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 100010;
static int h[] = new int[N], size, n, k;
public static void main(String[] args) throws IOException {
String ss[] = br.readLine().split(" ");
n = Integer.parseInt(ss[0]);
k = Integer.parseInt(ss[1]);
String[] s = br.readLine().split(" ");
for (int i = 1; i <= n; i++) h[i] = Integer.parseInt(s[i - 1]);
size = n;
for (int i = n >> 1; i >= 0; i-- ) down(i);
while (k-- > 0) {
pw.print(h[1] + " ");
h[1] = h[size--];
down(1);
}
pw.flush();
br.close();
}
private static void down(int x) {
int t = x;
if ((x << 1) <= size && h[x << 1] < h[t]) t = (x << 1);
if ((x << 1) + 1 <= size && h[(x << 1) + 1] < h[t]) t = (x << 1) + 1;
if (t != x) {
int temp = h[x];
h[x] = h[t];
h[t] = temp;
down(t);
}
}
}