堆排序之java
來源:互聯網
上載者:User
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();
}
}