二叉堆的实现
特性
- 结构性:
堆是一颗完全二叉树( complete binary tree ):一棵完全被填满的树,低层上的元素从左到右填入 - 堆序性
(以最小堆为例)最小堆的最小元在根上,并且每个子堆也都满足父节点不大于子节点
基本的堆操作
insert(插入)
- 在下一个可用位置添加一个空穴
- 将该空穴与其父元素比较,若
a. 空穴<父元素,交换两者位置,继续 2 操作
b. 空穴>=父元素,停止,将空穴赋值为带插入元素
上述操作称作上滤 ( percolate up )
- deleteMin(删除最小元)
- 在根节点建立空穴
- 将改空穴与其子元素比较,若
a. 空穴<=子元素,停止,将空穴赋值为结尾元素
b. 空穴>子元素,交换两者位置,继续2操作
需要注意的是,在选取子元素的时候,需要判断是否有左右节点,并选取两个子节点中较小的那个。上述操作称作下滤(percolate down)
- buildHeap(构建堆)
- 新建一个array
- copy元素
- 对于currentSize / 2 ~ 1 的每个元素进行下滤
- 完成堆构建
代码实现:
package dataStructures;
import java.util.ArrayList;
/*
* The Min Heap is built on an array.
* Elements are stored from 1 to currentsize.
*/
public class BinaryHeap<E extends Comparable<? super E>> {
public BinaryHeap() {
this(DEFAULT_CAPACITY);
}
public BinaryHeap(int capacity) {
currentSize = 0;
array = (E[])new Comparable[capacity];
}
public BinaryHeap(E[] items) {
currentSize = items.length;
array = (E[])new Comparable[(currentSize + 2) * 11 / 10];
int i = 1;
for(E item: items)
array[i++] = item;
buildHeap();
}
public void insert(E x) {
if(currentSize == array.length - 1)
enLargeArray(array.length * 2 + 1);
int hole = ++currentSize;
for(; hole > 0 && array[hole].compareTo(array[hole / 2]) < 0; hole /= 2)
array[hole] = array[hole / 2];
array[hole] = x;
}
public E findMin() {
return array[1];
}
public E deleteMin() {
if (isEmpty()) {
}
E minItem = findMin();
array[1] = array[currentSize--];
percolateDown(1);
return minItem;
}
public boolean isEmpty() {
return currentSize==0 ? true : false;
}
public void makeEmpty() {
}
private static final int DEFAULT_CAPACITY = 10;
private int currentSize;
private E[] array;
private void percolateDown(int hole) {
int child;
E tmp = array[hole];
for(; hole * 2 <= currentSize; hole = child) {
child = hole * 2;
if (child != currentSize && array[child].compareTo(array[child + 1]) > 0) {
child++;
}
if (array[hole].compareTo(array[child]) > 0) {
array[hole] = array[child];
} else {
break;
}
}
}
private void buildHeap() {
for(int i = currentSize / 2; i > 0; i--) {
percolateDown(i);
}
}
private void enLargeArray(int newSize) {
ArrayList<E> newArray = new ArrayList<E>(newSize);
for(int i = 0; i < currentSize; i++)
newArray.add(array[i]);
array = (E[]) newArray.toArray();
}
}