java简单实现大顶堆

// 添加一个元素方法
public void pushHeap(int[] heap, int value) {
    // 全局变量,记录堆的大小,添加时+1
    size++;
    // 把新增的元素放在最后
    heap[size - 1] = value;
    if (size == 1) {
        return;
    }
    // 有子节点的最后一个节点
    int loop = size / 2 - 1; 
    int newIndex = size - 1;
    while (loop > 0) {
        int index = loop;
        if (heap[newIndex] > heap[index]) {
            int tmp = heap[index];
            heap[index] = heap[newIndex];
            heap[newIndex] = tmp;
            newIndex = index;
        } else {
            break;
        }
        loop = (index + 1) / 2 - 1;
    }
}
// 推出一个顶端元素
public int pollHeap(int[] heap) {
    // 直接返回顶端元素
    int res = heap[0];
    // 最后一位元素放到顶端
    heap[0] = heap[size - 1];
    int index = 0;
    int left = 1;
    int right = 2;
    // 节点如果比子元素小就循环
    while (heap[index] < (Math.max(heap[left], heap[right]))) {
        int tmp = heap[index];
        // 找到最大的子节点,替代节点的位置
        if (heap[left] > heap[right]) {
            heap[index] = heap[left];
            heap[left] = tmp;
            index = left;
        } else {
            heap[index] = heap[right];
            heap[right] = tmp;
            index = right;
        }
        // 子节点的下标就是原本的下标*2 + 1
        left = index + index + 1;
        right = left + 1;
        if (left > size - 1) {
            break;
        }
    }
    // 把最后一位归0
    heap[size - 1] = 0;
    // 全局变量,记录堆的大小,推出时减1
    size--;
    return res;
}

// 测试用例
public void heap() {
    // 没有做扩容,就给了个不会溢出的值
    int[] heap = new int[20];
    this.pushHeap(heap, 6);
    this.pushHeap(heap, 3);
    this.pushHeap(heap, 4);
    this.pushHeap(heap, 14);
    this.pushHeap(heap, 12);
    this.pushHeap(heap, 24);
    this.pushHeap(heap, 22);
    this.pushHeap(heap, 34);
    this.pushHeap(heap, 2);
    this.pushHeap(heap, 5);
    this.pushHeap(heap, 1);
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
    System.out.println(pollHeap(heap));
}

没有做什么优化,当记个笔记了

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值