最大堆 进行升序排列
步骤
- 函数maxHeaptify(int a[], int s, int e)
- 在s 和 e 间构造大顶堆
- c = s, l = 2*c+1, tmp = a[c];
- 如果l < e 而且 a[l] < a[l+1], l++, (注意 l<e很重要,不然在多次heaptify时,已排好的会被重新纳入计算
- 比较a[c] 和 a[l] 如果已经满足 a[c] > a[l], 则停止。 这里可能会有疑问,为什么就停止了呢。其实我们保证只有根的节点破坏了大顶堆, 刚开始建堆时需要从 index = n-1/2 到 index = 0 进行maxHeaptify.
代码
#include <iostream>
void maxHeaptify(int a[], int s, int e)
{
int c = s;
int tmp = a[c];
int l = 2*c + 1;
for (;l <= e; c = l,l = 2*l+1)
{
// l < e very important, otherwise the last already sorted one will be re-calculated
if (l < e && a[l] < a[l+1]) l++;
if (a[c] > a[l]) break;
else
{
a[c] = a [l];
a[l] = tmp;
}
}
}
void heapSort(int a[], int n)
{
// firstly, build heap tree
for (int i = (n-1)/2; i >= 0; --i)
{
maxHeaptify(a, i, n-1);
}
for (int i = 0; i < n; ++i)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
for (int i = n-1; i >0; --i)
{
int tmp = a[0];
a[0] = a[i];
a[i] = tmp;
maxHeaptify(a, 0, i-1);
}
}
int main()
{
int a[] = {2, 3, 4, 5, 6, 2, 3, 4, 1};
int length = sizeof(a)/sizeof(a[0]);
heapSort(a, length);
for (int i = 0; i < length; ++i)
{
std::cout << a[i] << " ";
}
std::cout << std::endl;
return 0;
}
小顶堆本地sharpen文件夹也试了一遍。