#include <stdio.h>
#include <stdlib.h> // rand
void hpsort(unsigned long n, float ra[])
{
unsigned long i, ir, j, k;
float rra;
if (n < 2)
{
return;
}
/* The index k will be decremented from its initial value down to 1 during the “hiring” (heap
creation) phase. Once it reaches 1, the index ir will be decremented from its initial value
down to 1 during the “retirement-and-promotion” (heap selection) phase. */
k = (n >> 1) + 1;
ir = n;
for (;;)
{
if (k > 1)
{
rra = ra[--k];
}
else
{
rra = ra[ir];
ra[ir] = ra[1];
if (--ir == 1)
{
ra[1] = rra;
break;
}
}
i = k;
j = k + 1;
while (j <= ir)
{
if (j < ir && ra[j] < ra[j+1])
{
j++;
}
if (rra < ra[j])
{
ra[i] = ra[j];
i = j;
j <<= 1;
}
else
{
break;
}
}
ra[i] = rra;
}
}
int main()
{
float *a = (float *)malloc((8+1) * sizeof(float));
srand((unsigned int)time(NULL));
for (int i = 1; i <= 8; ++i) // 下标从1开始
{
a[i] = rand() % 23;
}
for (int i = 1; i <= 8; ++i)
{
printf("%f ", a[i]);
}
hpsort(8, a);
printf("\n-----------------------------------\n");
for (int i = 1; i <= 8; ++i)
{
printf("%f ", a[i]);
}
free(a);
return 0;
}
Reference
William H. Press et al. Numerical recipes in C : the art of scientific computing, 2nd ed.