/*
累堆排序
*/
#include <stdio.h>
void CM(int *a, int root, int index);
void Sort(int *a, int index);
int main()
{
int a[11] = {0, 1, 2, 3, 4, 7, 6, 10, 8, 9};
int i;
Sort(a, 10);
for(i = 1; i < 11; i++)
printf("%d ", a[i]);
printf("/n");
}
void Sort(int *a, int index)
{
int i, t;
for(i = index/2; i >= 1; i--)//第一次建堆
CM(a, i, index);
for(i = index; i >= 1; i--)//第二次建堆
{
t = a[1];
a[1] = a[i];
a[i] = t;
CM(a, 1, i - 1);
}
}
void CM(int *a, int root, int index)
{
int i, t, finish;
i = 2 * root;
t = a[root]; //父节点
finish = 0;//用于判断是否建好大根堆
while(i <= index && finish == 0)
{
if(i < index)
{
if(a[i] < a[i + 1])
i++;
}
if(t >= a[i])
finish = 1;
else
{
a[i / 2] = a[i];
i = 2 * i;
}
}
a[i / 2] = t;
}