Java实现大顶堆

1.前言

1.如果array[0,…,n-1]表示一颗完全二叉树的顺序存储模式,则双亲结点指针和孩子结点指针之间的内在关系如下

任意一结点指针i;父节点:i==0?null:(i-1)/2;
左子节点:2*i+1;
右子节点:2*i+2;

2.小顶堆

array[i]<=array[2*i+1] && array[i]<=array[2*i+2]

3.大顶堆

array[i]>=array[2*i+1] && array[i]>=array[2*i+2]

2.代码

public class MaxTopQueue {
    private int[] heap;
    private int maxSize;
    private int heapSize;
    public MaxTopQueue(int maxSize) {
        this.heap = new int[maxSize];
        this.maxSize = maxSize;
        this.heapSize = 0;
    }
    // 判断是否为空的方法
    public boolean isEmpty() {
        return heapSize == 0;
    }

    // 判断是否填满
    public boolean isFull() {
        return heapSize == maxSize;
    }

    // 获取堆顶的值
    public int peek() {
        if (heapSize == 0) {
            throw new RuntimeException("heap is empty");
        }
        return heap[0];
    }

    // 往堆中添加值
    public void offer (int value) {
        if (heapSize == maxSize) {
            throw new RuntimeException("head is full");
        }
        heap[heapSize] = value;
        heapSize++;
        buildMaxHeap(heap);
    }

    // 删除堆顶值
    public int poll() {
        if (heapSize == 0) {
            throw new RuntimeException("heap is empty");
        }
        int ans = heap[0];
        swap(heap,0,--heapSize);
        buildMaxHeap(heap);
        return ans;
    }

    // 建大顶堆
    private int[] buildMaxHeap(int[] array) {
        for (int i = (heapSize-2)/2; i >= 0; i--) {
            adjustDownToUp(array,i,heapSize);
        }
        return array;
    }
	
    private void adjustDownToUp(int[] array, int index, int length) {
        int temp = array[index];
        for (int i = 2*index+1; i < length; i = 2*i+1) {
            if (i < length-1 && array[i] < array[i+1]) {
                i++;
            }
            if (temp >= array[i]) {
                break;
            } else {
                array[index] = array[i];
                index = i;
            }
        }
        array[index] = temp;
    }
	// 交换元素值
    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // 获取所有元素
    public List<Integer> getAllElements() {
        List<Integer> ans = new ArrayList<>();
        for (int i = 0; i < heapSize; i++) {
            ans.add(heap[i]);
        }
        return ans;
    }
	// 堆排序
    /*public void heapSort() {
        for (int i = heapSize-1; i >= 0; i--) {
            swap(heap,0,i);
            adjustDownToUp(heap,0,i);
        }
    }*/
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Listen·Rain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值