C. Heap Sort
输入样例:
31,41,59,26,53,58,97,
2
#include <stdio.h>
#include <stdlib.h>
void percolateDown(int a[], int top, int p);
int main()
{
int a[200];
char b[200];
int x = 0;
int top = 0;
gets(b);
for (int i = 0; b[i] != '\0'; i++)
{
if (b[i] != ',')
{
x = 10 * x + b[i] - '0';
}
else if (b[i] == ',')
{
a[++top] = x;
x = 0;
}
}
int round;
scanf("%d", &round);
int NO = 1;
//build the max heap;
for (int i = top / 2; i > 0; i--)
{
percolateDown(a, top, i);
}
int n = top;
if (round == 1)
{
for (int k = 1; k <= n; k++)
{
printf("%d,", a[k]);
}
printf("\n");
}
for (int i = n; i >= 1; i--)
{
int temp = a[i];
a[i] = a[1];
a[1] = temp;
percolateDown(a, --top, 1);
NO++;
if (round == NO)
{
for (int k = 1; k <= n; k++)
{
printf("%d,", a[k]);
}
printf("\n");
}
}
return 0;
}
void percolateDown(int a[], int top, int p)
{
int judge = a[p];
int child;
int i;
for (i = p; 2 * i <= top; i = child)
{
child = 2 * i;
if (child != top && a[child + 1] > a[child])
{
child++;
}
if (judge < a[child]) //因为要建立的堆 大的元素在上面 ,这里要写不符合情况
{
a[i] = a[child];
}
else
{
break;
}
}
a[i] = judge;
}