AcWing 838. Java 大顶堆排序模板
原题链接
简单
作者:
iqqcode
,
2020-10-17 07:33:15
,
所有人可见
,
阅读 578
import java.util.*;
public class Solution {
// 排序
public static void heapSort(int[] arr) {
// 构建大顶堆
buildHeap(arr);
for (int i = arr.length - 1; i >= 0; i--) {
swap(arr, i, 0);
heapify(arr, i, 0);
}
}
// 构建堆
public static void buildHeap(int[] arr) {
int last_node = arr.length - 1;
int parent = (last_node - 1) >> 1;
for (int i = parent; i >= 0; i--) {
heapify(arr, arr.length, i);
}
}
// 堆调整
public static void heapify(int[] arr, int len, int root) {
if (root >= len) return;
int left = 2 * root + 1;
int right = 2 * root + 2;
int max = root;
if (right < len && arr[max] < arr[right]) {
max = right;
}
if (left < len && arr[max] < arr[left]) {
max = left;
}
if (max != root) {
swap(arr, max, root);
heapify(arr, len, max);
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
}