什么是堆?
要想实现堆,先要知道什么是堆和堆都有那些操作。
**堆(英语:heap)**是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵树的数组对象。堆总是满足下列性质:
- 堆中某个节点的值总是不大于或不小于其父节点的值;
- 堆总是一棵完全二叉树。
通俗的说堆是使用数组保存二叉树结构,方式即将二叉树用层序遍历方式放入数组中。 一般只适合表示完全二叉树,因为非完全二叉树会有空间的浪费。 这种方式的主要用法就是堆的表示。
堆有哪些特性?
已知双亲(parent)的下标,则:
左孩子(left)下标 = 2 * parent + 1;
右孩子(right)下标 = 2 * parent + 2;
已知孩子(不区分左右)(child)下标,则:
双亲(parent)下标 = (child - 1) / 2;
- 堆逻辑上是一棵完全二叉树
- 堆物理上是保存在数组中
- 满足任意结点的值都大于其子树中结点的值,叫做大堆,或者大根堆,或者最大堆
- 反之,则是小堆,或者小根堆,或者最小堆
堆的主要操作
错误处理 | 抛出异常 | 返回特殊值 |
---|---|---|
入堆 | add(e) | offer(e) |
出堆 | remove() | poll() |
堆顶元素 | element() | peek() |
堆的实现
public class MyPriorityQueue {
private int[] array = new int[100];
private int size = 0;
//入堆
public void offer(int x) {
if (size >= array.length) {
return;
}
array[size] = x;
size++;
shiftUp(array, size - 1);
}
//向下调整
private static void shiftDown(int[] array, int size, int index) {
int parent = index;
int child = parent * 2 + 1;
while (child < size) {
if (child + 1 < size && array[child + 1] > array[child]) {
child = child + 1;
}
if (array[child] > array[parent]) {
swap(array, parent, child);
} else {
break;
}
parent = child;
child = parent * 2 + 1;
}
}
//向上调整
private static void shiftUp(int[] array, int index) {
int child = index;
int parent = (child - 1) / 2;
while (child > 0) {
if (array[parent] < array[child]) {
swap(array, parent, child);
}else {
break;
}
child = parent;
parent = (child - 1) / 2;
}
}
//出堆顶元素
public Integer poll() {
if (size == 0) {
return null;
}
int ret = array[0];
array[0] = array[size - 1];
size--;
shiftDown(array, size, 0);
return ret;
}
private static void swap(int[] array, int x, int y) {
int temp = array[x];
array[x] = array[y];
array[y] = temp;
}
//查看堆顶元素
public Integer peek() {
if (size == 0) {
return null;
}
return array[0];
}
public static void main(String[] args) {
MyPriorityQueue myPriorityQueue = new MyPriorityQueue();
myPriorityQueue.offer(9);
myPriorityQueue.offer(5);
myPriorityQueue.offer(2);
myPriorityQueue.offer(7);
myPriorityQueue.offer(3);
myPriorityQueue.offer(8);
while (myPriorityQueue.peek() != null) {
int a = myPriorityQueue.poll();
System.out.print(a + " ");
}
}
}