二叉堆是一种特殊的堆,具有如下的特性:
原文链接
public class binaryheap {
/*
* 上浮
* length:二叉堆的长度
*/
public int[] upAdjust(int arr[],int length) {
int child = length-1;
int parent = (length-1)/2;
int temp = arr[child];
//进行上浮
while(child>0&&temp<arr[parent]) {
arr[child]=arr[parent];
child = parent;
parent = (child-1)/2;
}
arr[child]=temp;
return arr;
}
/*
* 下沉:执行删除操作相当于把最后一个元素赋给根元素之后,认购对根元素执行下沉操作
*
*/
public int[] downAdjust(int arr[],int parent,int length) {
//临时保证要下沉的元素
int temp = arr[parent];
//定位左孩子
int child = 2*parent+1;
//开始下沉
while(child<length) {
if(child+1<length&&arr[child]>arr[child]+1) {
child++;
}
//如果父节点比孩子结点小或者等于,则下沉结束
if(temp<=arr[child]) {
break;
}
arr[parent]=arr[child];
parent = child;
child = parent*2+1;
}
arr[parent]=temp;
return arr;
}
/*
* 创建二叉堆
*
*/
public int[] build(int arr[],int length) {
for(int i=(length-2)/2;i>=0;i--) {
arr=downAdjust(arr, i, length);
}
return arr;
}
}