二叉堆的本质还是数组,完全二叉堆是建立完全二叉树的基础上的,二叉堆又分为大顶堆和小定堆,大顶堆就是父节点的值大于左右孩子的两个节点的值,小顶堆就是父节点的值小于左右孩子节点的值。堆的自我调整包括删除节点和添加节点,添加节点是在二叉堆的最后一个位置上添加,删除节点是删除根节点的值。然后左右孩子的重新调整成一个二叉堆。二叉堆的构建就是让一个无序的完全二叉树调成成二叉堆,本质就是让所有非叶子节点上升或者下沉。
存储方式:是顺序存储不是链式存储
计算方式:是通过数组的下标 假设父节点是parent 左孩子节点的值是2parent+1 有孩子节点的值是2parent+2;
下面看看代码:`
package shujujiegou;
import java.util.Arrays;
public class HeapOperator {
//上浮调整
public static void upAdjust(int[] array) {
int childIndex=array.length-1;
int parentIndex=(childIndex-1)/2;
int temp=array[childIndex];//用于保存叶子节点的的值
while(childIndex>0&&temp<array[parentIndex]) {
//无需正真赋值,只需单向赋值
array[childIndex]=array[parentIndex];
childIndex=parentIndex;
parentIndex=(childIndex-1)/2;
}
array[childIndex]=temp;
}
//下沉调整
public static void downAdjust(int[] array,int parentIndex,int length) {
int temp=array[parentIndex];
int childIndex=2*parentIndex+1;
while(childIndex<length) {
//如果有右孩子,且右孩子节点的值小于左孩子节点的值,则定位到右孩子
if(childIndex+1<length&&array[childIndex]>array[childIndex+1]) {
childIndex++;
}
//如果父节点小于所有的子节点,则跳出循环
if(temp<=array[childIndex]) {
break;
}
//无需正真交换只需要单项赋值
array[parentIndex]=array[childIndex];
parentIndex=childIndex;
childIndex=parentIndex*2+1;
}
array[parentIndex]=temp;
}
public static void buildHeap(int[] array) {
for(int i=array.length/2;i>=0;i--) {
downAdjust(array, i, array.length-1);
}
}
public static void main(String[] args) {
int[] array=new int[]{1,2,4,2,3,6,7};
upAdjust(array);
System.out.println(Arrays.toString(array));
}
}