- 逻辑意义上是一棵完全二叉树
- 物理意义上存储在数组中
向下调整
大根堆为例
public static void adjustDown(int[] elem,int root, int len) {
int parent = root;
int child = 2 * parent + 1;
while (child < len) {
//判断是否有右孩子,且谁最大
if (child + 1 < len && elem[child] < elem[child + 1]) {
child = child + 1;
}
if (elem[child] > elem[parent]) {
//child肯定是左右孩子最大值的下标
int t = elem[child];
elem[child] = elem[parent];
elem[parent] = t;
parent = child;
child = 2 * parent + 1;
}else{
break;
}
}
}
建堆
public static void createHeap(int[] array){
for (int i = (array.length-1-1)/2; i >= 0 ; i--) {