前言
上节内容我们介绍了优先级队列的实现方法,即通过向上调整和向下调整算法实现创建大根堆或者小根堆。本节内容我们将比较这两种算法,找出其优劣;
我们先举例对于这样一个数组来建立一个小根堆;
一、向上调整来建堆
思想:
其过程的图解:
代码实现:
????????????????具体时间
public class Test2 {
private int[] array;
private int usedSize; // 当前堆中的有效元素个数
Test2() {
array = new int[10]; // 通过构造方法给数组分配空间
}
// 向上调整保证是小根堆:时间复杂度是O(log以2为底的N)---log2N
public void shiftUp(int child) {
int parent = (child - 1) / 2;
while (parent >= 0) {
if (this.array[child] < this.array[parent]) {
int tmp = this.array[child];
this.array[child] = array[parent];
this.array[parent] = tmp;
child = parent;
parent = (child - 1) / 2;
}
else {
break;
}
}
}
// 向堆中插入元素
public void offerHeap(int val) {
if (this.usedSize >= this.array.length) {
System.out.println("数组已满,插入失败!");
}
else {
this.array[usedSize] = val;
shiftUp(usedSize); // 插入数据后进行向上调整确保为小堆
++usedSize; // 堆中有效元素加一个
}
}
// 向上调整建立小根堆,时间复杂度是O(n * log2N)
public void createHeapUp() {
int[] a = {4, 2, 7, 8, 5, 1, 0, 6};
// 遍历a数组,将a数组中的元素一个一个的插入堆中
for (int i = 0; i < a.length; i++) {
offerHeap(a[i]);
}
}
public static void main(String[] args) {
Test2 test2 = new Test2();
test2.createHeapUp();
}
}
运行结果:
代码示例:
二、向下调整来建堆
根据该数组建立小根堆
思路:
分析过程的图解 :
三、向上建堆和向下建堆的优劣比较
我们看一下他们各自的时间复杂度 :
举例说明:
有一棵满完全二叉树:
对于向上建堆计算:
对于向下建堆计算:
综上,向下建堆其实性能更好一定;