Java实现堆

堆数据结构

堆是一颗完全二叉树,所以其往往用数组来实现。堆中的数据是局部有序的,这种有序是父结点与子结点之间的有序。

有两种不同的堆

最大值堆的性质是任意一个结点的值都大于或等于任意一个子结点存储的值。

最小值堆的性质是任意一个结点的值都小于或等于任意一个结点存储的值。

这里实现最大值堆

package binaryTree;

public class MaxHeap {
	private Object[] heap;
	private int size;
	private int n;
	private void siftDown(int pos)
	{
		while(!isLeaf(pos))
		{
			int j = leftChild(pos);
			int rc = rightChild(pos);
			if((rc < n) && ((int)heap[j] < (int)heap[rc]))
			{
				j = rc;
			}
			if((int)heap[pos] >= (int)heap[j])
				return;
			swap(heap,pos,j);
			pos = j;
		}
	}
	private void swap(Object[] obj,int i,int j)
	{
		Object temp;
		temp = obj[i];
		obj[i] = obj[j];
		obj[j] = temp;
	}
	
	public MaxHeap(Object[] heap,int size,int n)
	{
		this.heap = heap;
		this.size = size;
		this.n = n;
	}
	
	public int heapSize()
	{
		return n;
	}
	
	public boolean isLeaf(int pos)
	{
		return (pos >= n/2) && (pos < n);
	}
	
	public int leftChild(int pos)
	{
		return 2*pos + 1;
	}
	
	public int rightChild(int pos)
	{
		return 2*pos + 2;
	}
	
	public int parent(int pos)
	{
		return (pos - 1)/2;
	}
	
	public boolean insert(Object obj)
	{
		if(n >= size)
			return false;
		int curr = n++;
		heap[curr] = obj;
		while((curr != 0) && ((int)heap[curr] > (int)heap[parent(curr)]))
		{
			swap(heap,curr,parent(curr));
			curr = parent(curr);
		}
		return true;	
	}

	public Object removeMax()
	{
		if(n == 0)
			return false;
		swap(heap,0,--n);
		if(n != 0)
			siftDown(0);
		return heap[n];
	}
	
	public Object remove(int pos)
	{
		if((pos < 0) || (pos >= n))
		{
			return null;
		}
		swap(heap,pos,--n);
		while((pos != 0) && (int)heap[pos] > (int)heap[parent(pos)])
		{
			swap(heap,pos,parent(pos));
		}
		siftDown(pos);
		return heap[n];
	}
	
	public void buildHeap()
	{
		for(int i = n/2 - 1;i >= 0;i--)
		{
			siftDown(i);
		}
	}
	public void print()
	{
		for(int i = 0;i < n;i++)
		{
			System.out.print(heap[i] + " ");
		}
		System.out.println();
	}
	public static void main(String[] args)
	{
		Object[] a = {4,2,45,56,23,43,6567};
		MaxHeap mh = new MaxHeap(a,20,a.length);
		mh.print();
		mh.buildHeap();
		mh.print();
	}
}

请无视main函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值