1.前言
1.如果array[0,…,n-1]表示一颗完全二叉树的顺序存储模式,则双亲结点指针和孩子结点指针之间的内在关系如下
任意一结点指针i;父节点:i==0?null:(i-1)/2;
左子节点:2*i+1;
右子节点:2*i+2;
2.小顶堆
array[i]<=array[2*i+1] && array[i]<=array[2*i+2]
3.大顶堆
array[i]>=array[2*i+1] && array[i]>=array[2*i+2]
2.代码
public class MaxTopQueue {
private int[] heap;
private int maxSize;
private int heapSize;
public MaxTopQueue(int maxSize) {
this.heap = new int[maxSize];
this.maxSize = maxSize;
this.heapSize = 0;
}
// 判断是否为空的方法
public boolean isEmpty() {
return heapSize == 0;
}
// 判断是否填满
public boolean isFull() {
return heapSize == maxSize;
}
// 获取堆顶的值
public int peek() {
if (heapSize == 0) {
throw new RuntimeException("heap is empty");
}
return heap[0];
}
// 往堆中添加值
public void offer (int value) {
if (heapSize == maxSize) {
throw new RuntimeException("head is full");
}
heap[heapSize] = value;
heapSize++;
buildMaxHeap(heap);
}
// 删除堆顶值
public int poll() {
if (heapSize == 0) {
throw new RuntimeException("heap is empty");
}
int ans = heap[0];
swap(heap,0,--heapSize);
buildMaxHeap(heap);
return ans;
}
// 建大顶堆
private int[] buildMaxHeap(int[] array) {
for (int i = (heapSize-2)/2; i >= 0; i--) {
adjustDownToUp(array,i,heapSize);
}
return array;
}
private void adjustDownToUp(int[] array, int index, int length) {
int temp = array[index];
for (int i = 2*index+1; i < length; i = 2*i+1) {
if (i < length-1 && array[i] < array[i+1]) {
i++;
}
if (temp >= array[i]) {
break;
} else {
array[index] = array[i];
index = i;
}
}
array[index] = temp;
}
// 交换元素值
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// 获取所有元素
public List<Integer> getAllElements() {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < heapSize; i++) {
ans.add(heap[i]);
}
return ans;
}
// 堆排序
/*public void heapSort() {
for (int i = heapSize-1; i >= 0; i--) {
swap(heap,0,i);
adjustDownToUp(heap,0,i);
}
}*/
}