堆排序之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();
}


}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.