HeapSort

Heapsort is a comparison-based sorting algorithm to create a sorted array (or list), and is part of theselection sort family. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but it is not a stable sort.

 1 /*
 2  * Best     Average    Worst     Memory   Stable
 3  * nlogn     nlogn     nlogn       1       No
 4 */
 5 public class HeapSort {
 6     
 7     private static int[] input = new int[] {16, 14, 10, 8, 7, 9, 3, 2, 4, 1}; 
 8     
 9     public static void heapSort(int[] a){
10         int length=a.length;
11         buildMaxHeap(a, length);
12         for(int i=length-1;i>0;i--){
13             int temp=a[i];
14             a[i]=a[0];
15             a[0]=temp;
16             maxHeapify(a, 1, i);
17         }
18     }
19     
20     public static void buildMaxHeap(int[] a,int heapSize){
21         for(int i=heapSize/2;i>0;i--){
22             maxHeapify(a, i,heapSize);
23         }
24     }
25     
26     public static void maxHeapify(int[] a,int index,int heapSize){
27         int l=index*2;
28         int r=l+1;
29         int largest;
30         if(l<=heapSize && a[l-1]>a[index-1]){
31             largest=l;
32         }
33         else{
34             largest=index;
35         }
36         if(r<=heapSize && a[r-1]>a[largest-1]){
37             largest=r;
38         }
39         if(largest != index){
40             int temp=a[index-1];
41             a[index-1]=a[largest-1];
42             a[largest-1]=temp;
43             maxHeapify(a,largest,heapSize);
44         }
45         
46     }
47     
48     public static void printArray(int[] a){
49         for(int i = 0;i < a.length;i++){
50             System.out.print(a[i]+" ");
51         }
52     }
53     
54     public static void main(String[] args) {
55         // TODO Auto-generated method stub
56         heapSort(input);
57         printArray(input);
58     }
59 
60 }

 

 

posted on 2013-03-30 10:05  melotang  阅读(146)  评论(0)    收藏  举报