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]+",");
}
}
}