堆排序(Heap Sort)算法的实现
2010-07-17 02:07
513 查看
堆排序算法思想非常简单,先把一个数组看成一个heap, 在下面的实现中,我使用的是max heap, 也就是说根总是比叶子大。所以我们第一步就是建立max heap。建立完毕以后,很明显这个heap的root就是最大的,把最大的根放在数组的最后一个位置,把数组长度缩小一个位置,这样最大的那个数就不会再参与到下次的排序当中,这时,除了根以外,heap的其它部分都保持max heap的特性,所以我们需要再做一次max heap (只对根做),再把最大的放在目前被缩小的数组的最后一个位置,重复下去,知道数组中只剩下一个数。
MaxHeapify的时间复杂度为 O(lgn), 所以整个heap sort的复杂度为:O(n lgn).
转载请注明出处: http://blog.csdn.net/beiyeqingteng
class HeapSortAlgorithm { public void HeapSort(int[] array) { int heapSize = array.length; for (int i = array.length / 2 - 1; i >= 0; i--) { MaxHeapify(array, i, array.length); } for (int i = array.length - 1; i > 0; i--) { swap(0, i, array); heapSize--; MaxHeapify(array, 0, heapSize); } } /// MaxHeapify is to build the max heap from the 'position' public void MaxHeapify(int[] array, int position, int heapSize) { int left = left(position); int right = right(position); int maxPosition = position; if (left < heapSize && array[left] > array[position]) { maxPosition = left; } if (right < heapSize && array[right] > array[maxPosition]) { maxPosition = right; } if (position != maxPosition) { swap(position, maxPosition, array); MaxHeapify(array, maxPosition, heapSize); } } /// return the left child position public int left(int i) { return 2 * i + 1; } /// return the right child position public int right(int i) { return 2 * i + 2; } }
MaxHeapify的时间复杂度为 O(lgn), 所以整个heap sort的复杂度为:O(n lgn).
转载请注明出处: http://blog.csdn.net/beiyeqingteng
相关文章推荐
- 算法珠玑--再看堆排序(Heap Sort)的实现
- 算法学习 - 堆排序 ( HeapSort ) C++实现
- 堆排序(Heap Sort)算法的实现
- PHP实现排序堆排序(Heap Sort)算法
- HeapSort——堆排序实现(算法类)
- 堆排序(Heap Sort) 算法实现 C语言版
- c++堆排序实现(heapsort) (算法导论)
- 算法珠玑--再看堆排序(Heap Sort)的实现
- Java堆排序(HeapSort)算法实现
- Heap Sort堆排序 Java语言实现
- [转载]堆排序(HeapSort) Java实现
- heap sort算法实现
- 图解排序算法及C语言实现之 ------ 堆排序:Heap Sort
- 堆排序Heap Sort——浅显易懂+Java实现
- Atitit 算法之道 attilax著 1. 第二部分(Part II) 排序与顺序统计(Sorting and Order Statistics) 1 2. 第六章 堆排序(Heapsort)
- 算法总结系列之一:堆排序(Heap Sort)
- 堆排序(HeapSort) Java实现
- (转)算法总结系列之一:堆排序(Heap Sort)
- 堆排序Heap Sort——浅显易懂+Java实现
- Java实现---堆排序 Heap Sort