算法__优先队列

最大优先队列:无论入队顺序,最大的数字先出队;

最小优先队列:无论入队顺序,最小的数字先出队;

754231 

二叉树:

 插入一个数字 8:

  8  大于 4,4和8交换;  8 大于7 ,8和7交换。

代码如下:

/**
 * 优先排序(最大优先队列)
 */
public class TestPro {

    //队列的大小
    private int size = 32;
    private int[] arrays;
    //下一个需要存储的坐标
    private int position = 0;

    public TestPro() {
        arrays = new int[size];
    }

    public TestPro(int size) {
        arrays = new int[size];
    }

    /**
     * 添加数据
     *
     * @param number 数值
     */
    public void enQueue(int number) {
        if (position >= size)
            reSize();
        arrays[position++] = number;
        upJust();
    }

    /**
     * 输出最大的值
     *
     * @return 最大值
     * @throws Exception 没有值了
     */
    public int outQueue() throws Exception {
        if (position <= 0)
            throw new Exception("没有值可出了。。。");

        int head = arrays[0];
        arrays[0] = arrays[--position];
        downJust();
        return head;
    }

    /**
     * 扩张一倍数组
     */
    private void reSize() {
        size = size * 2;
        arrays = Arrays.copyOf(arrays, size);
    }

    /**
     * 上浮调整
     */
    private void upJust() {
        int childIndex = position - 1;
        int lastNumber = arrays[childIndex];
        int parentIndex = (childIndex - 1) / 2;
        while (childIndex > 0 && lastNumber > arrays[parentIndex]) {
            arrays[childIndex] = arrays[parentIndex];
            childIndex = parentIndex;
            parentIndex = (childIndex - 1) / 2;
        }
        arrays[childIndex] = lastNumber;
    }

    /**
     * 下沉调整
     */
    private void downJust() {
        int childIndex = 1, parentIndex = 0;
        int parentNumber = arrays[0];
        while (childIndex < position) {
            if (childIndex + 1 < position && arrays[childIndex + 1] > arrays[childIndex]) {
                childIndex++;
            }

            if (parentNumber > arrays[childIndex])
                break;

            arrays[parentIndex] = arrays[childIndex];
            parentIndex = childIndex;
            childIndex = parentIndex * 2 + 1;
        }
        arrays[parentIndex] = parentNumber;
    }

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值