《算法》基于堆的优先队列

优先队列:能够插入元素,能够删除最大元素。
堆(二叉堆):父节点大于等于子节点,左右子节点大小不定;
在一个堆中,位置为k的节点的父节点位置为⌊k/2⌋(向下取整符号),子节点为2k和2k+1。

//基于堆的优先队列,《算法》p202
package algorithm;

public class MaxPQ_p202 {
    private int[] pq = new int[100];
    int N = 0;
    public void insert(int a){
        pq[++N] = a;
        swim(N);
    }
    public int delMax(){
        int Max = pq[1];
        exch(1, N--);
        pq[N+1] = 0;
        sink(1);
        return Max;
    }   
    private void swim(int k){           //上浮
        while((k > 1) && (pq[k/2] < pq[k])){
            exch(k/2, k);
            k = k/2;
        }
    }
    private void sink(int k){           //下沉
        while(2*k <= N){
            int j = 2*k;
            if ((j < N) && (pq[j] < pq[j+1])){j++;}
            if(!(pq[k] < pq[j])) break;
            exch(k, j);
            k = j;
        }       
    }
    private void exch(int i, int j){    //交换
        int temp = pq[i];
        pq[i] = pq[j];
        pq[j] = temp;
    }
    public void display(){
        for(int i = 1; i <= N; i++){
            System.out.println(pq[i]);
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MaxPQ_p202 test = new MaxPQ_p202();
        test.insert(0);
        test.insert(1);
        test.insert(2);
        test.insert(3);
        test.insert(4);
        test.insert(5);
        System.out.println("插入0~5后:");
        test.display();
        test.delMax();
        System.out.println("删除最大值后:");
        test.display();     
    }

}

结果

插入0~5后:
5
3
4
0
2
1
删除最大值后:
4
3
1
0
2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值