题目要求:
第一部分现根据输入的数字建立一个最大堆,并且print出来。
第二部分要求这个最大堆的每个非叶结点的右儿子都要大于等于他的左儿子。
请问第二部分该怎么写?
第一部分写出来这个最大堆是数组的形式,怎么判断哪些是叶子结点,并按照要求重新排序。还是说第一部分做最大堆的时候就不该怎么处理。
希望能有详细的代码或者解释,谢谢。
以下是第一部分
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
void maxheapify(int *, int, int);
int* buildmaxheap(int *, int);
void main()
{
int i, t, n;
int *a = calloc(MAX, sizeof(int));
int *m = calloc(MAX, sizeof(int));
printf("输入元素的个数\n");
scanf("%d", &n);
printf("输入数字\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
m = buildmaxheap(a, n);
printf("The heap is\n");
for (t = 0; t < n; t++) {
printf("%d\n", m[t]);
}
}
int* buildmaxheap(int a[], int n)
{
int heapsize = n;
int j;
for (j = n/2; j >= 0; j--) {
maxheapify(a, j, heapsize);
}
return a;
}
void maxheapify(int a[], int i, int heapsize)
{
int temp, largest, left, right;
left = (2*i+1);
right = ((2*i)+2);
if (left >= heapsize)
return;
else {
if (left < (heapsize) && a[left] > a[i])
largest = left;
else
largest = i;
if (right < (heapsize) && a[right] > a[largest])
largest = right;
if (largest != i) {
temp = a[i];
a[i] = a[largest];
a[largest] = temp;
maxheapify(a, largest, heapsize);
}
}
}
例子
Enter no of elements in the array
5
Enter the array
7
5
9
3
2
The heap is :
9
5
7
3
2