堆排序算法(Java實現)


將待排序的序列構造成一個大頂堆(從大到小排要構造成小頂堆)。此時,整個序列的最大值就是堆頂的根節點,將他和末尾元素交換,然后將剩余的length-1個節點序列重新構造成新的堆。重復執行,便能得到一個有序序列。

 1 package sort;
 2 
 3 public class HeapSort {
 4     static void heapSort(int []a,int len){
 5         int i;
 6         for(i=len/2;i>=0;i--){ /*把a[]構造成一個大頂堆*/
 7             HeapAdjust(a,i,len);
 8         }
 9         for(i=len;i>0;i--){
10             swap(a,0,i); /*交換堆頂最大元素和堆尾最小元素*/
11             HeapAdjust(a,0,i-1);  /*把交換后的堆a[0,i-1],再次構造成大頂頂,使堆頂元素為最大值*/
12         }
13     }
14     static void HeapAdjust(int []a,int start,int len){
15         int temp,j;
16         temp=a[start];
17         for(j=2*start;j<=len;j*=2){   /*從index最大的有孩子的節點開始篩選,堆排*/
18             if(j<len&&a[j]<a[j+1])    /*是index=j的元素為較大的元素*/
19                 j++;
20             if(temp>=a[j])
21                 break;
22             a[start]=a[j];            /*將較大元素賦值給父節點*/
23             start=j;
24         }
25         a[start]=temp;              
26     }
27     static void swap(int a[],int low,int high){
28         int temp=a[low];
29         a[low]=a[high];
30         a[high]=temp;
31     }
32     public static void main(String []args){
33         int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 };
34         heapSort(b, b.length - 1);
35         for(int w:b)
36             System.out.print(" "+w);
37     }
38 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM