堆基于数据的实现

堆是完全二叉树
底层数组实现-------k结点的两个子节点 2k和2k+1
每个结点都大于他的子节点

Api

public void insert(T t){
	//0索引被废弃
	items[++N] = t;
	swim(N);
}

public void swim(int k){
	//上浮    
	while(k>1){
		if(less(k/2,k)){
			exch(k/2,k);
		}
	}
	k=k/2;
}

public T delMax(){
	T max = item[1];
	exch(1,N);
	items[N] = null;
	N--;
	sink(1);
	return max;
	
	
}

public void sink(int k){
	//下沉
	while(2*k <= N){
		int max ;
		if(2*k+1<=N){
			if(less(2k,2k+1)){
				max = 2*k+1;	
			}else{
				max = 2*k;
			}
			if(!less(k,max)){
			break;
			}
			exch(k,max);
			k=max;
		}
		
	}
}

-堆排序

private static void createHeap(Comparable[] source ,Comparable[] heap){
	System.arraycopy(source,0,heap,1,source.length);
	for(int i =heap.length/2 ; i>0;i--){
		sink(heap,i,heap.length-1);
	}
}

public static void sort(Comparable[] source){
	Comparable[] heap = new Comparable[source.length+1];
	createHeap(source,heap);
	int N = heap.length-1;
	while(N!=1){
		exch(heap,1,N);
		N--;	
		sink(heap,1,N);
	}
	System.arraycopy(heap,1,source,0,source.length); 
}

public static void sink (Comparable[] heap, int target, int range){
	while(2*target<range){
		int max;
		if(2*target+1<=range){
			if(less(heap,a*target,2*target+1)){
				max = 2*target +1 ;
			}else{
				max = 2*target; 
			}
		}else{
			max = 2*target;
		}
		if(!less(heap , target,max)){
		break;}
		exch(heap,target,max);
		target = max ;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值