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); } }
相关文章推荐
- 堆排序 HeapSort
- PAT (Advanced Level) Practise 1098 Insertion or Heap Sort (25)
- 09-排序3 Insertion or Heap Sort
- 堆积排序-堆排序-heap sort
- 堆排序算法的实现(HeapSort)
- Algorithms:HeapSort
- 每天一个小算法(Heapsort)
- 堆排序(Heap Sort)
- 堆--堆排序--heap--heap_sort
- 算法导论学习-heapsort
- 堆排序(Heapsort)
- 堆排序(HeapSort)
- 1098. Insertion or Heap Sort (25)
- 1098. Insertion or Heap Sort (25)
- heapSort_by_Java
- 堆排序(HeapSort)
- Pat(Advanced Level)Practice--1098( Insertion or Heap Sort)
- Heapsort
- heap sort in python :-) just for fun
- 堆排序(Heap Sort) 算法实现 C语言版