小根堆实现

public class MinHeap {

	private int[] heap;
	private int length;
	public MinHeap(int[] arr){
		if(arr.length<=0){
			throw new IllegalArgumentException("array length illegal");
		}
		heap = new int[arr.length];
		System.arraycopy(arr, 0, heap, 0, arr.length);
		length = arr.length;
		createHeap();
	}

	private void createHeap(){
		//从倒数第一个非叶节点的节点开始,向下调整,构建小根堆
		for(int i=length/2-1;i>=0;i--){
			fixDown(i);
		}
		System.out.println(Arrays.toString(heap));
	}

	private void fixUp(int index){
		int c = index;
		int p = (index-1)/2;
		int tmp = heap[index];
		while(p>=0){
			if(heap[p]<=tmp){
				break;
			}else{
				heap[c] = heap[p];
				c=p;
				p = (p-1)>>1;
			}
		}
		heap[c] =tmp; 
	}

	private void fixDown(int index){
		int p =index;
		int c = index*2+1;
		int tmp =heap[index];
		while(c<length){
			//找到孩子节点最小的索引
			if(c<length-1&&heap[c] > heap[c+1]){
				c++;
			}

			if(heap[c]>=tmp&&heap[c]>=tmp){
				break;
			}else{
				heap[p] = heap[c];
				p = c;
				c = 2*c+1;
			}
		}
		heap[p] = tmp;
	}
	//用最后一个节点覆盖要删除的节点,从删除节点的位置向下调整
	public int delete(int index){
		if(index>=length){
			throw new IllegalArgumentException("index out of bound");
		}
		int ret = heap[index];
		heap[index] = heap[length-1];
		length--;
		fixDown(index);
		return ret;
	}

	//添加到最后的位置,然后从最后的位置向上调整
	public void add(int value){
		if(length==heap.length){
			int[]tmp = new int[length+16];
			System.arraycopy(heap, 0, tmp, 0,length);
			this.heap = tmp;
		}
		heap[length]=value;
		fixUp(length);
		length++;
	}

	//删除第一个几点,每删除一次,从头开始向下调整
	public int pop(){
		int ret=heap[0];
		heap[0] = heap[length-1];
		length--;
		fixDown(0);
		return ret;
	}
	
	public static void main(String[] args) {
		MinHeap heap = new MinHeap(new int[]{10,2,62,85,2,4,23,222,3,1});
		heap.delete(0);
		int l=heap.length;
		for(int i=0;i<l;i++){
			System.out.println(heap.pop());
		}
	}

}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值