- 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).
No comments:
Post a Comment