您的位置:首页 > 其它

HeapSort

2013-03-30 10:05 295 查看
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.

/*
* Best     Average    Worst     Memory   Stable
* nlogn     nlogn     nlogn       1       No
*/
public class HeapSort {

private static int[] input = new int[] {16, 14, 10, 8, 7, 9, 3, 2, 4, 1};

public static void heapSort(int[] a){
int length=a.length;
buildMaxHeap(a, length);
for(int i=length-1;i>0;i--){
int temp=a[i];
a[i]=a[0];
a[0]=temp;
maxHeapify(a, 1, i);
}
}

public static void buildMaxHeap(int[] a,int heapSize){
for(int i=heapSize/2;i>0;i--){
maxHeapify(a, i,heapSize);
}
}

public static void maxHeapify(int[] a,int index,int heapSize){
int l=index*2;
int r=l+1;
int largest;
if(l<=heapSize && a[l-1]>a[index-1]){
largest=l;
}
else{
largest=index;
}
if(r<=heapSize && a[r-1]>a[largest-1]){
largest=r;
}
if(largest != index){
int temp=a[index-1];
a[index-1]=a[largest-1];
a[largest-1]=temp;
maxHeapify(a,largest,heapSize);
}

}

public static void printArray(int[] a){
for(int i = 0;i < a.length;i++){
System.out.print(a[i]+" ");
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
heapSort(input);
printArray(input);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: