public void removeMax() {
if (count == 0) return -1; // 堆中没有数据
a[1] = a[count];
--count;
heapify(a, count, 1);
}
private 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;
}
}
/**
* 构建堆 从下标1到下标n
* 从后往前处理数组,每个数据都是从上往下堆化
*/
private static void buildHeap(int[] a, int n) {
for (int i = n / 2; i >= 1; --i) {
heapify(a, n, i);
}
}
/**
* 堆化操作 将数组a中,以i开始,n结束的数组调整为大根堆
*/
private static void heapify(int[] a, int n, int i) {
while (true) {
int maxIndex = i;
if (i * 2 <= n && a[maxIndex] < a[i * 2]) {
maxIndex = i * 2;
}
if (i * 2 + 1 <= n && a[maxIndex] < a[i * 2 + 1]) {
maxIndex = i * 2 + 1;
}
//已经是大根堆了
if (maxIndex == i) {
break;
}
swap(a, i, maxIndex);
//指针i移动到maxIndex下标处,继续进行下层堆化
i = maxIndex;
}
}