数据结构与算法-java实现二叉堆的基本操作

package com_DataStructureAndAlogorithm_Learning;

public class BinaryHeap_2<AnyType extends Comparable<?super AnyType>>{
	private static final int DEAFAULT_CAPACITY=10;
	private int currentSize;
	private AnyType[] array;//The heap array;
	
	public BinaryHeap_2() {
		this(DEAFAULT_CAPACITY);
	}
	public BinaryHeap_2(int capacity) {
		currentSize = 0;
		array=(AnyType[])new Comparable[capacity+1];
	}
	public BinaryHeap_2(AnyType[] items) {
		currentSize=items.length;
		array=(AnyType[])new Comparable[(currentSize+2)*11/10];
		int i=1;
		for(AnyType item:items) {
			array[i++]=item;
		}
		buildHeap();
	}
	
	public void insert(AnyType x) {
		if(currentSize==array.length-1) {
			enlargeArray(array.length*2+1);//扩展数组
		}
		int hole=++currentSize;
		for(array[0]=x;x.compareTo(array[hole/2])<0;hole/=2) {
			array[hole]=array[hole/2];
		}
		array[hole]=x;
	}
	/**
	 * 
	 * @param hole
	 */
	private void percolateDown(int hole) {
		int child;
		AnyType tmp=array[hole];
		for(;hole*2<=currentSize;hole=child) {
			child=hole*2;
			if(child!=currentSize && array[child+1].compareTo(array[child])<0) {
				child++;
			}
			if(array[child].compareTo(tmp)<0) {
				array[hole]=array[child];
			}
			else
				break;
		}
		array[hole]=tmp;
		
	}
	private void buildHeap() {
		for(int i=currentSize/2;i>0;i--) {
			percolateDown(i);
		}		
	}
	private void enlargeArray(int newSize) {
		AnyType[] oldArr=array;
		array=(AnyType[])new Comparable[newSize];
		for(int i=0;i<oldArr.length;i++) {
			array[i]=oldArr[i];
		}
	}
	
	public AnyType findMin() {
		return array[1];
	}
	public boolean isEmpty() {
		return currentSize==0;
	}
	public AnyType deleteMin() {
		AnyType minItem=array[1];
		array[1]=array[currentSize--];
		percolateDown(1);
		return minItem;
	}
	public void makeEmpty() {
		currentSize=0;
	}
    public static void main(String[]args) {
        int numItems = 10000;
        BinaryHeap_2<Integer> h = new BinaryHeap_2<>();
        int i = 37;

        for (i = 37; i != 0; i = (i + 37) % numItems)
            h.insert(i);
        for (i = 1; i < numItems; i++)
            if (h.deleteMin() != i)
                System.out.println("Oops! " + i);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值