堆结构(一)
-
堆结构总结:
1)堆结构就是用数组实现的完全二叉树结构
2)完全二叉树中如果每棵子树的最大值都在顶部就是大根堆
3)完全二叉树中如果每棵子树的最小值都在顶部就是小根堆
4)堆结构的heapInsert与heapify操作
5)堆结构的增大和减少
6)优先级队列结构,就是堆结构 -
show code
public static class MaxHeap {
private int[] heap;
private final int limit;
private int heapSize;
public MaxHeap (int limit) {
heap = new int[limit];
this.limit = limit;
heapSize = 0;
}
public boolean isEmpty() {
return heapSize == 0;
}
public boolean isFull() {
return heapSize == limit;
}
public void push(int value) {
if (heapSize == limit) {
throw new RuntimeException("heap is full");
}
heap[heapSize] = value;
// value heapSize
heapInsert(heap, heapSize++);
}
// 用户此时,让你返回最大值,并且在大根堆中,把最大值删掉
// 剩下的数,依然保持大根堆组织
public int pop() {
int ans = heap[0];
swap(heap, 0, --heapSize);
heapify(heap, 0, heapSize);
return ans;
}
// 上浮
private void heapInsert(int[] arr, int index) {
// arr[index]
// arr[index] 不比 arr[index父]大了 , 然后停止
// index = 0;
while (arr[index] > arr[(index - 1) / 2]) {
swap(arr, index, (index - 1) / 2); // 交换
index = (index - 1) / 2; // 父节点
}
}
// 下沉
// 从index位置,往下看,不断的下沉,
// 停:我的孩子都不再比我大;已经没孩子了
private void heapify(int[] arr, int index, int heapSize) {
int left = index * 2 + 1; // 左孩子
while (left < heapSize) {
// 左右两个孩子中,谁大,谁把自己的下标给largest
// 右 -> 1) 有右孩子 && 2)右孩子的值比左孩子大才行
// 否则,左
int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
largest = arr[largest] > arr[index] ? largest : index;
if (largest == index) {
break;
}
swap(arr, largest, index);
index = largest;
left = index * 2 + 1;
}
}
private void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}