AcWing 838. Java堆排序 使用类似插入排序算法的方式进行优化的最大堆
原题链接
简单
作者:
LeonLiu
,
2019-12-04 17:45:46
,
所有人可见
,
阅读 1150
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] l1 = br.readLine().split(" ");
int n = Integer.parseInt(l1[0]), m = Integer.parseInt(l1[1]);
String[] l2 = br.readLine().split(" ");
int[] arr = new int[l2.length + 1];
for (int i = 1; i <= n; i++) {
arr[i] = Integer.parseInt(l2[i - 1]);
}
for (int i = n >>> 1; i >= 1; i--) {
shiftDown(arr, i, n);
}
for (int i = n; i > 1; i--) {
arr[i] = arr[i] ^ arr[1] ^ (arr[1] = arr[i]);
shiftDown(arr, 1, i - 1);
}
for (int i = 1; i <= m; i++) System.out.print(arr[i] + " ");
br.close();
}
private static void shiftDown(int[] arr, int idx, int limit) {
int x = arr[idx];
while (true) {
int l = idx << 1, r = l + 1, m = l;
if (l > limit) break;
if (r <= limit && arr[r] > arr[m]) m = r;
if (x > arr[m]) break;
arr[idx] = arr[m];
idx = m;
}
arr[idx] = x;
}
}