Java heap的实现 最小堆的实现 代码简洁

public class HeapMin {
	private int[] Heap;
	private int maxsize;
	private int size;


	public HeapMin(int max) {
		maxsize = max;
		Heap = new int[maxsize];
		size = 0;
		Heap[0] = Integer.MIN_VALUE;
	}


	private int leftchild(int pos) {
		return 2 * pos;
	}


	private int rightchild(int pos) {
		return 2 * pos + 1;
	}


	private int parent(int pos) {
		return pos / 2;
	}


	private boolean isleaf(int pos) {
		return ((pos > size / 2) && (pos <= size));
	}


	private void swap(int pos1, int pos2) {
		int tmp;
		tmp = Heap[pos1];
		Heap[pos1] = Heap[pos2];
		Heap[pos2] = tmp;
	}


	public void insert(int elem) {
		size++;
		Heap[size] = elem;
		int current = size;
		while (Heap[current] < Heap[parent(current)]) {
			swap(current, parent(current));
			current = parent(current);
		}
	}


	public void print() {
		int i;
		for (i = 1; i <= size; i++)
			System.out.print(Heap[i] + " ");
		System.out.println();
	}


	public int removemin() {
		swap(1, size);
		size--;
		if (size != 0)
			pushdown(1);
		return Heap[size + 1];
	}


	private void pushdown(int position) {
		int smallestchild;
		while (!isleaf(position)) {
			smallestchild = leftchild(position);
			if ((smallestchild < size)
					&& (Heap[smallestchild] > Heap[smallestchild + 1]))
				smallestchild = smallestchild + 1;
			if (Heap[position] <= Heap[smallestchild])
				return;
			swap(position, smallestchild);
			position = smallestchild;
		}
	}


	public static void main(String args[])
	{
		HeapMin hm = new HeapMin(6);
		hm.insert(1);
		hm.insert(30);
		hm.insert(50);
		hm.insert(20);
		hm.insert(70);
		hm.print();
		
	}
}


insert函数包含了ShiftUp的过程。pushDown就是ShiftDown的过程。

要变成最大堆,只需要修改这两个过程的大于小于

来源:http://wenwen.soso.com/z/q278758109.htm
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值