#include<iostream>
#include<cstdlib>
#define SIZE 10
using namespace std;
void HeapSort(int a[], int n)
{
int i, j, k, h;
int t;
for (i = n / 2 - 1; i >= 0; i--)
{
while (2*i+1<n)
{
j = 2 * i + 1;
if ((j + 1) < n)
{
if (a[j] < a[j + 1])
j++;
}
if (a[i] < a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
i = j;
}
else
{
break;
}
}
}
cout << "输出堆 :" << endl;
for (h = 0; h < n; h++)
cout << a[h] << " ";
cout << endl;
for (i = n - 1; i > 0; i--)
{
t = a[0];
a[0] = a[i];
a[i] = t;
k = 0;
while (2 * k + 1 < i)
{
j = 2 * k + 1;
if ((j + 1) < i)
if (a[j + 1] > a[j])
j++;
if (a[k] < a[j])
{
t = a[k];
a[k] = a[j];
a[j] = t;
k = j;
}
else
break;
}
cout << "第 " << n - i << " 步排序结果" << endl;
for (h = 0; h < n; h++)
cout << a[h] << " ";
cout << endl;
}
}
int main()
{
int a[10] = { 3,5,9,8,0,1,2,7,6,10 };
int n = 10;
for (int i = 0; i < 10; i++)
cout << a[i] << " ";
cout << endl;
HeapSort(a, 10);
for (int i = 0; i < 10; i++)
cout << a[i] << " ";
system("pause");
return 0;
}
参考自C++常用算法手册