標籤:
/* ***********完完整整的用堆排序來對一個序列進行排序 ************ * */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 實現