栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Heap的java实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684830.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号