堆是一颗完全二叉树,所有父节点都满足小于等于其子节点的堆称为小根堆,所有父节点都满足大于等于其子节点的堆称为大根堆,堆虽然是一棵树,但是通常存放在一棵数组,父节点和子节点的关系通常通过元素下标来确定。
从图中,我们可以很容易的总结出,通过一个节点数组中的索引怎么计算出它的父节点及左右孩子节点。
public int left (int i){
return ((i+1)*2-1);
}
public int right (int i){
return ((i+1)*2);
}
public int parent (int i){
if(i==0)
return -1;
else
return (i-1)/2;
}
要构建一个堆,除了知道怎么计算一个节点的父节点和孩子节点的索引之外,还需要知道两个算法,保持堆的性质和建堆,建堆的方法对于大根堆和小根堆是一样的。
保持堆的性质,对与大根堆和小根堆很相似,但不完全一样,所以要分开说。
已经存在的两个大根堆,现在要把一个元素,作为这两个大根堆的根的父节点,构成一个新堆,但是这个堆的根节点可能不太符合大根堆的性质,可能他比他的孩子节点小,所以需要对它进行操作,操作的方式就是,我们从这个节点和他的孩子节点选出最大的,如果这个节点是最大的,堆就已经满足大根堆的性质了,否则将这个节点与最大节点交换,交换后该节点在新的位置上也可能违背大根堆的性质,所以需要递归的进行直至这个节点比孩子节点都大或者是子节点为止
package com.java.day11;
/**
* Created by wangkaishuang on 18-4-17
*/
public class HeadDemo {
static int left(int i){
return ((i+1)*2-1);
}
static int right(int i){
return ((i+1)*2);
}
static int parent(int i){
if(i==0)
return -1;
else
return (i-1)/2;
}
//大根堆
static void maxHeapify(int[] a, int i, int heapLenth){
int l = left(i);
int r = right(i);
int largest = -1;
if(l<heapLenth && a[i]<(a[l])){
largest = l;
}
else
largest = i;
if(r<heapLenth && a[largest]<a[r]){
largest = r;
}
if(i != largest){
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
maxHeapify(a,largest,heapLenth);
}
}
//小根堆
void minHeapify(int[] a,int i,int heapLenth){
int l = left(i);
int r = right(i);
int smallest = -1;
if(l<heapLenth && a[i] > a[l]){
smallest= l;
}
else
smallest = i;
if(r<heapLenth && a[smallest]>(a[r])){
smallest = r;
}
if(i != smallest){
int temp = a[i];
a[i] = a[smallest];
a[smallest] = temp;
minHeapify(a,smallest,heapLenth);
}
}
//建堆
static void buildHeap(int[] a, int heapLenth){
int lenthParent = parent(heapLenth-1);
for(int i=lenthParent;i>=0;i--){
maxHeapify(a,i,heapLenth);
}
}
public static void main(String[] args){
int a[] ={1,3,5,7,9};
buildHeap(a,5);
for(int c : a)
System.out.println(c);
}
}