//基本思路:
//1.把一个数组按下表构造成一个完全二叉树
//2.找到数组的最后一个元素(最后一个叶子结点),判断它在左子树上还是右子树上
//3.如果在左子树上,直接拿该结点与它的父结点比较,如果比父结点大,与父结点交换位置
//4.如果在右子树上,左右子树先比较大小,把大的放在右子树上,再将右子树与父结点比较,把大的放在父节点上
//5.查找到倒数第二个父结点,重复它的子树的构建堆过程,直到查找到根结点为止。
//6.把此时的根结点放在数组的最后一位上(此时根结点是该堆的最大值),重复上诉过程,直到排好序为止。
#include<iostream>
using namespace std;
#define N 10
void heapsort(int a[], int num)
{
int temp, i = 0;
int num0 = num;
if (num == 0)
{
cout << "没有输入数据";
return;
}
if (num == 1)
return;
while (num != 1)
{
while (num != 1)
{
if (num % 2 == 0)
{
if (a[num - 1] >= a[num / 2 - 1])
{
temp = a[num - 1];
a[num - 1] = a[num / 2 - 1];
a[num / 2 - 1] = temp;
}
}
else
{
if (a[num - 1] <= a[num - 2])
{
temp = a[num - 2];
a[num - 2] = a[num - 1];
a[num - 1] = temp;
}
if (a[num - 1] >= a[num / 2 - 1])
{
temp = a[num - 1];
a[num - 1] = a[num / 2 - 1];
a[num / 2 - 1] = temp;
}
}
num = (num / 2 - 1) * 2 + 1;
}
i++;
temp = a[0];
a[0] = a[num0 - i];
a[num0 - i] = temp;
num = num0 - i;
}
}
int main()
{
int a[N] = { 67, 65, 77, 38, 97, 3, 33, 49, 50, 42 };
int i;
heapsort(a, N);
for (i = 0; i < N; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}