堆排序之java

import java.math.*;
import java.util.*;


public class Main {

public static void  MaxHeap(int[] tt,int pos,int len){
int temp=tt[pos];
/*System.out.println("temp"+temp);*/
int child;
/**
* 下面的child=pos*2+1的意思为什么不是要求的左子树是pos*2,右子树是pos*2+1呢,这需要思考一下。
* 这里要判断pos*2+1<=len-1来确定pos的左子树是不是到达数组的末尾了,而为什么不是判断pos*2+2<=len-1,
* 这是因为如果判断pos*2+2<=len-1(判断右子树是否在数组范围以内了)的话,如果右子树如果没在数组范围以内,
* 那么他就把符合要求的左子树要刷掉,这是不公平的,所以只能先判断左子树,判断完之后再根据是否有右子树进行进一步
* 的判断。
*/
for(;pos*2+1<=len-1;pos=child){     
child=pos*2+1;
if(child<len-1&&tt[child]<tt[child+1]) child++;
if(temp<tt[child]) {
/*System.out.println("temp="+temp+"  change:"+tt[pos]+","+tt[child]);*/
tt[pos]=tt[child];

}
else break;
}
tt[pos]=temp;
}
public static void sortHeap(int[] tt,int len){
if(len<=1) return ;
/**
* 这里的i=len/2-1这个范围不是固定的,按照建堆的方法,从只要在整个数组一半后面就可以了,重建堆他
* 会自己去判断是否满足重建堆。

*/
for(int i=len/2-1;i>=0;i--){  
MaxHeap(tt,i,len);
}
System.out.println("create done");
/*for(int j=0;j<len;j++){
System.out.print(tt[j]+" ");
}
System.out.println();*/
System.out.println("sort:");
/**
* MaxHeap(tt,0,i)里的i一定要是i,不能是i-1,这是要按照重建堆的方法来的。i对应的是需要重建堆的数组的长度len定的。
*/
for(int i=len-1;i>=0;i--){
int temp=tt[i];
tt[i]=tt[0];
tt[0]=temp;
MaxHeap(tt,0,i);

/*for(int j=0;j<len;j++){
System.out.print(tt[j]+" ");
}
System.out.println();*/
}
}
public static void main(String[] args) {
int tt[]={2,3,1,6,9,10,11};
int len=tt.length;
sortHeap(tt,len);
Scanner s=new Scanner(System.in);
s.close();
for(int i=0;i<len;i++){
System.out.print(tt[i]+" ");
}
System.out.println();
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值