建立一个小顶堆;
建立时保证左子树右子树大于根节点;
去掉堆顶;
然后把最后一项放在堆顶,然后再调整保证左子树右子树大于根节点;
再去掉堆顶;
以此类推;
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "请输入数组长度:" << endl;
cin >> n;
int *NUM = new int[n];
cout << "请输入" << n << "个元素" << endl;
for (int i = 0; i < n; i++)
{
int j = i, temp;
cin >> NUM[i];
while (j > 0)
{
if (NUM[((j - 1) / 2)] > NUM[j])
{
temp = NUM[(j - 1) / 2];
NUM[(j - 1) / 2] = NUM[j];
NUM[j] = temp;
}
j = (j - 1) / 2;
}
}
while (n > 0)
{
int temp, tt;
cout << NUM[0] << endl;
NUM[0] = NUM[n - 1];
n--;
temp = 0;
while (((2 * temp + 1) < n) && ((2 * temp + 1) < n))
{
if ((NUM[temp] <= NUM[temp * 2 + 1]) && (NUM[temp] <= NUM[temp * 2 + 2]))
{
break;
}
else
{
if (NUM[temp * 2 + 1] < NUM[temp * 2 + 2])
{
tt = NUM[temp];
NUM[temp] = NUM[temp * 2 + 1];
NUM[temp * 2 + 1] = tt;
temp = temp * 2 + 1;
}
else
{
tt = NUM[temp];
NUM[temp] = NUM[temp * 2 + 2];
NUM[temp * 2 + 2] = tt;
temp = temp * 2 + 2;
}
}
}
}
delete[]NUM;
return 0;
}