堆有大顶堆和小顶堆,以小顶堆为例,每个父亲结点比它的左右孩子结点都要小,但不要求孩子结点有序,即可以左孩子大于右孩子,也可以右孩子大于左孩子。堆注重的是堆顶,小顶堆的堆顶一定是最小的,大顶堆的堆顶一定是最大的,这种数据结构被应用于优先级队列,每次队列出优先级最高的那个,而不注重其余元素的顺序和他们入队的先后次序。
优先级队列常被应用到任务调度场景中,每次调度优先级最大的任务,而不注重其它任务何时进入队列,在队列中以何顺序排列。
下面介绍堆的两个重要的操作,插入和删除
伪代码:假设当前数组的长度元素个数为n(下标1~n),新加入一个元素
void add(int val){
heap[++n] = val; //加入堆的尾部
for(int i=n; i!=1 && heap[i] < heap[i/2];i=i/2)
swap(heap[i],heap[i/2]);
}
伪代码:
int poll(){
int res = heap[1]; //返回结果
//调整
heap[1] = heap[n--]; //堆尾变为堆顶
//child<=n是保证有孩子
for(int father = 1,child=2*father; child<=n; father=child,child=2*father){
if(child+1 <= n && heap[child+1] < heap[child]) child++;
swap(heap[father],heap[child]);
}
return res;
}
java实现,实现方法有很多,代码也可不一样,重要的是理解原理
class Heap {
ArrayList<Integer> heap;
Heap(){
heap = new ArrayList<>();
heap.add(0);
}
public void add(int val){
heap.add(val);
for(int i=heap.size()-1;i!=1 && heap.get(i).compareTo(heap.get(i/2)) < 0;i=i/2)
swap(i,i/2);
}
public int poll(){
int res = heap.get(1);
heap.set(1,heap.get(heap.size()-1));
heap.remove(heap.size()-1);
for(int father=1,child=2*father; child< heap.size(); father=child,child=2*father){
if(child+1 < heap.size() && heap.get(child+1).compareTo(heap.get(child)) < 0) child++;
swap(father,child);
}
return res;
}
private void swap(int a,int b){
int tmp = heap.get(a);
heap.set(a,heap.get(b));
heap.set(b,tmp);
}
public void print(){
for(int i=1;i<heap.size();i++)
System.out.printf("%d ",heap.get(i));
System.out.println();
}
public boolean isEmpty(){
return heap.size() == 1;
}
}
public class main {
public static void main(String[] args){
Heap heap = new Heap();
int [] arr = new int[]{80,11,82,13,57,138,3,4};
System.out.println("add:");
for(int t : arr){
heap.add(t);
heap.print();
}
System.out.println("\npoll:");
while(!heap.isEmpty()){
System.out.println(heap.poll());
}
}
}
运行结果:
堆的构建时间复杂度为N,调整时间复杂度为logN
堆的构建是指把一棵无序二叉树调整为顶堆,构建是自底向上的,叶节点跟父节点比较,不满足顶堆性质就交换,最坏情况全部父节点都被换到叶节点,那么所花的时间为2^(H-1)*1,2^(H-1)是指父节点这层即H-1层有2^(H-1)个结点(根为0层,叶节点为H层),最多下调一层,那么第i层调整的时间为2^i*(H-i),把每层相加,再把H=logN带入能得到结果s= 2N - 2 - log2(N),近似O(N)
调整时间复杂度,无论是自底向上,还是自顶向下,最多有H次结点交换,所以调整时间复杂度为logN