堆排序的java 實現

來源:互聯網
上載者:User

標籤:

/* ***********完完整整的用堆排序來對一個序列進行排序 ************ * */import java.util.Random;public class HeapSort {    public static void main(String args[]){        int[] a = new int[1050];        InitList(a);//初始化        PrintList(a);//列印隨機產生的序列
     System.out.println();//列印一行空格,區分排序前還是排序後
new HeapSort().Heap_Sort(a); PrintList(a);//列印排序之後的序列 } /* ********************HeapSort****************** * */ public void Heap_Sort(int a[]){ int length = a.length; //建造一個堆 CreatHeap(a,length); for(int i = length ; i > 0 ; i-- ){ //把最小的放到最後邊,然後重新構造小頂堆 int temp = a[0]; a[0] = a[i-1]; a[i-1] = temp; CreatHeap(a,i-1); } } /* ********************構造小頂堆********************* * */ public void CreatHeap(int a[],int length){ //從最後一個非分葉節點開始,一個個逐漸向前調整來構造一個小頂堆 for(int i = length/2 ; i >=0 ; i--){ HeapAdjust(a,i,length); } } /* ************************調整小頂堆 ************************ * */ public void HeapAdjust(int a[],int pos,int length){ //pos為待調整節點,leftChild為待調整節點的左孩子,rightChild為帶調整節點的右孩子 int leftChild = pos*2; int rightChild = pos*2+1; int min = pos; if(leftChild<length && a[leftChild]<a[min]){ min = leftChild; } if(rightChild<length && a[rightChild]<a[min]){ min = rightChild; } if(min !=pos){// 調整當前節點,若有比當前節點小的節點,則交換 int temp = a[pos]; a[pos] = a[min]; a[min] = temp; //交換後的節點可能會不滿足小頂堆,則遞迴調整交換後的節點 //若min==pos,即上述交換過程沒發生,則也不會執行次遞迴調整的過程 HeapAdjust(a,min,length); } //調整當前節點的孩子節點 } public static void InitList(int[] a){ Random intr = new Random(); for(int i = 0 ; i < a.length ; i ++){ a[i] =intr.nextInt(1000); } } public static void PrintList(int[] a){ for(int i = 0 ; i < a.length ; i ++){ System.out.print(a[i]+ " "); } }}

 

堆排序的java 實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.