目录
一、堆的概念以及堆的创建
1、堆的概念
什么是堆?(堆的逻辑上是一个完全二叉树,实际上是保存在数组中)
我们把一个完全二叉树通过层序遍历存储到数组当中,这个数组就叫做堆。
注意:堆中的元素不能为空。(浪费大量空间)
什么是大根堆和小根堆?
大根堆:所有结点的值都大于其子结点的值,我们称为大根堆。
小根堆:所有结点的值都小于其子结点的值,我们称为小根堆。
注意:父亲结点为i时,左孩子的结点为i*2+1,右孩子的结点为i*2+2;
孩子结点为i时,父亲结点为(i-1)/2;
2、堆的创建
2.1向下遍历
对于堆中的排序我们可以采用向下遍历的方法,我们就拿小堆的向下遍历来做例子。
2.2建堆操作
由于堆的底层是数组,我们开始要创建一个数组并且初始化。
public class TestHeap {
public int[] elem;
public int uesdSize;
public TestHeap(){
this.elem=new int[10];
}
}
接下来我们要将一段无序的数组放进去,并且通过elem数组拷贝进来,同时我们通过由下向上不断遍历由上向下的函数。
public void createBigHeap(int[] array){
for(int i=0;i<array.length;i++){
this.elem[i]=array[i];
this.usedSize++;
}
for(int i=(this.usedSize-1-1)/2;i>=0;i--){
shiftDown(i);
}
}
接下来我们编写由上向下的函数shiftDown(i);
public void shiftDown(int parent){
int child=parent*2+1;
while (child<this.usedSize){
if(child+1<this.usedSize && this.elem[child+1]<this.elem[child]){
child++;
}
if(this.elem[parent]>this.elem[child]){
int temp=this.elem[parent];
this.elem[child]=this.elem[parent];
this.elem[parent]=temp;
parent=child;
child=child*2+1;
}else {
break;
}