java 堆排序

java堆排序数字方式实现
/**
 * 堆排序核心思想,建立二叉堆,执行N次delete操作
 * @author 
 *
 */
public class HeapSort {
	/**
	 * 
	 * @param <T>
	 * @param a
	 */
	public static <T extends Comparable<? super T>> void heapSort(T [] a){
		for(int i=a.length/2;i>=0;i--){
			procDown(a,i,a.length);//创建堆
		}
		for(int i=1,len=a.length;i<a.length;i++,len--){
			exchange(a, 0,len-1);
			procDown(a,0,len-1);//这两步相当于delete操作,将删除的元素放到数组后面的位置,节省空间,之后下虑重新建堆
		}
	}
	/**
	 * 将某一个位置上的元素下虑
	 * @param <T>
	 * @param a
	 * @param pos位置
	 * @param len可用数组长度
	 */
	public static <T extends Comparable<? super T>> void procDown(T [] a,int pos,int len){
		T tmp=a[pos];
		int childPos=findChild(pos);
		for(;childPos<len;childPos=findChild(pos)){
			if(childPos+1!=len&&a[childPos].compareTo(a[childPos+1])<0){
				childPos=childPos+1;
			}
			if(tmp.compareTo(a[childPos])<0){
				a[pos]=a[childPos];
				pos=childPos;
			}else{
				break;
			}
		}
		a[pos]=tmp;
	}
	/**
	 * 计算左儿子节点的位置
	 * @param pos
	 * @return
	 */
	public static int findChild(int pos){
		return 2*pos+1;
	}
	/**
	 * 
	 * @param <T>
	 * @param a
	 * @param pos1
	 * @param pos2
	 */
	public static <T extends Comparable<? super T>> void exchange(T [] a,int pos1,int pos2){
		T tmp=a[pos1];
		a[pos1]=a[pos2];
		a[pos2]=tmp;
		
	}
	public static void main(String[] args) {
		Integer a []={8,6,9,2,5,100,25,48,1,6,8,46,7864,54};
		heapSort(a);
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+",");
		}
		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值