public class HeapSort {
public static void main(String[] args) {
int A[] = {0, 4, 3, 5, 1, 6};
System.out.println(Arrays.toString(A));
sort(A, A.length-1);
System.out.println(Arrays.toString(A));
}
public static void sort(int[] a, int n) {
buildHeap(a, n);
int k = n;
while (k > 1) {
swap(a, 1, k);
--k;
heapify(a, k, 1);
}
}
private static void buildHeap(int[] a, int n) {
for (int i = n / 2; i >= 1; --i) {
heapify(a, n, i);
}
}
private static void heapify(int[] a, int n, int i) {
while (true) {
int maxPos = i;
if (i * 2 <= n && a[i] < a[i * 2]) maxPos = i * 2;
if (i * 2 + 1 <= n && a[maxPos] < a[i * 2 + 1]) maxPos = i * 2 + 1;
if (maxPos == i) break;
swap(a, i, maxPos);
i = maxPos;
}
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
堆操作: 入堆:放到数组最后,然后堆化 出堆:删除堆顶元素,将数组最后一个元素放到堆顶,堆化 建堆: 1.遍历入队操作 nlog 2. 从下到上初始化,从下表n/2开始,向前遍历,堆化 O(n) 原理: 先构建最大/最小堆,然后逐个出堆. 时间复杂度分析: 构建时间复杂度n,出堆排序log(n)