最大堆的特性:最大堆的最大元素在根部,其余元素遵从A[PARENT(i)] >= A[i]
其中数组A的首元素A[0]保存堆的大小
代码如下:maxheap.c
#include <stdio.h>
#define PARENT(x) (x)/2
#define LEFT(x) 2*(x)
#define RIGHT(x) 2*(x)+1
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void max_heapify(int A[], int index)
{
int l = LEFT(index);
int r = RIGHT(index);
int large = -1;
if (l <= A[0] && A[l] > A[index])
large = l;
else large = index;
if (r <= A[0] && A[r] > A[large])
large = r;
if (large != index)
{
swap(&A[large], &A[index]);
max_heapify(A, large);
}
}
void build_max_heap(int A[])
{
int i;
for (i = A[0]/2; i >= 1; i--)
max_heapify(A, i);
}
int main(void)
{
int i = 0;
int A[11] = {10, 4, 1, 3, 2 ,16, 9, 10, 14, 8, 7};
build_max_heap(A);
for (i = 0; i < 11; i++)
printf("%d ", A[i]);
printf("\n");
return 0;
}
输出结果:
10 16 14 10 8 7 9 3 2 4 1