#include <iostream>
using namespace std;
// 对arr[i]为根的子树建堆;i:根节点下标 n:堆大小
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// main function to do heap sort
void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void printArray(int arr[], int n)
{
for (int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);
}
堆排序对相同长度的数组比较次数是固定的,时间性能是稳定的O(nlogn)。
但缺点也同样在此,哪怕对于一个有序的数组,堆排序要耗费同样的时间排序。
《算法导论》上讲基数排序还有这么一句话:快速排序通常比基数排序更有效地使用硬件的缓存。 因为快排是顺着扫的,堆排序是跳着走的;快排的存取模型的局部性(locality)更强,,堆排序差一些。
所以大多情况下,快排要比堆排序更快。