Heap的java实现

本文介绍了Heap数据结构,特别是MaxHeap的实现。通过数组操作,详细阐述了如何在Java中构建始终保持根节点为最大值的MaxHeap。
摘要由CSDN通过智能技术生成
  • heap是一种特殊的二叉树,始终将最大值或最小值留在二叉树根节点上,分别是MaxHeap和MinHeap实现
  • MinHeap与MaxHeap的实现区别在于大小比较相反
  • 这里以MaxHeap实现为例,本场景下使用数组操作更方便,所以此处使用数组实现
public class MaxHeap {
	private int capacity;
	private int size = 1;
	private int[] tree;
	public MaxHeap(int capacity) {
		this.capacity = capacity;
		this.tree = new int[capacity];
	}
	// remove root node and poll new root node
	public int poll() {
		if(size-1 == 0) throw new NoSuchElementException();
		int value = tree[1];
		tree[1] = tree[--size];
		int index = 1,leftIndex = 2,rightIndex = 3;
		while(rightIndex <size) {
			if(tree[leftIndex] > tree[rightIndex]) {
				swap(leftIndex,index);
				index = leftIndex;
			}else {
				swap(rightIndex,index);
				index = rightIndex;
			}
			leftIndex = index*2;
			rightIndex = index*2+1;
		}
		if(leftIndex < size) swap(leftIndex,index);
		return value;
	}
	// peek root node
	public int peek() {
		if(size-1 == 0) throw new NoSuchElementException();
		return tree[1];
	}
	public void push(int value) {
		// check capacity
		if(size==capacity) {
			capacity*=2;
			this.tree = Arrays.copyOf(tree, capacity);
		}
		tree[size++] = value;
		riseUpMax();
	}
	// update root node
	public void riseUpMax() {
		int index = size-1;
		while(index != 1) {
			int parentIndex = index/2;
			if(tree[index] > tree[parentIndex]) {
				swap(index,parentIndex);
				index = parentIndex;
			}else break;
		}
	}
	public void swap(int index1,int index2) {
		int temp;
		temp = tree[index1];
		tree[index1] = tree[index2];
		tree[index2] = temp;
	}
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("tree:\n");
		int index = 1;
		for(int i =  1; i < size; i++) {
			sb.append(String.format("%-3d", tree[i]));
			if(i==index) {
				sb.append("\n");
				index=index*2+1;
			}
		}
		return sb.toString();
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

安河桥北久铭心

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

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

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

打赏作者

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

抵扣说明:

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

余额充值