Heap的java实现

Heap的java实现,第1张

Heap的java实现
  • 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  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;
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5685379.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存