From bottom up for each node or only for each non-leaf node use the "keep heap nature" that is the "heap adjustment" MAX-HEAPIFY
# Include <stdio. h> # include <string. h> # include <time. h> # define buffer_size 10 void maxheapify (int * a, int I, int heapsize) {int left = I; int right = I; int TMP; int largest = I; while (I <= heapsize) {left = I <1; // right = (I <1) + 1; // (the shift operation has a lower priority than the arithmetic operation !) Right sub-index largest = I; If (left <= heapsize & A [I] <A [left]) {largest = left ;} if (right <= heapsize & A [Largest] <A [right]) {largest = right;} if (I! = Largest) // an endless loop may occur if you do not add this judgment. In this case, you can compress {TMP = A [I]; A [I] = A [Largest]; A [Largest] = TMP; I = largest; // actually, the amount of recursive changes to be eliminated depends on the number of} else {break ;}} void output (int *, int Len) {int I = 1; for (I = 1; I <= Len; I ++) {printf ("% d", a [I]);} printf ("\ n");} void buildmaxheap (int * a, int heapsize) {int I = 0; for (I = buffer_size/2; I> 0; I --) {maxheapify (A, I, heapsize) ;}} int main () {int I = 0; int A [buffer_size + 1]; // The first position is a [0]. Therefore, it is easy to calculate the index of a subnode. Memset (A, 0, sizeof (a); srand (unsigned) Time (null); for (I = 1; I <= buffer_size; I ++) {A [I] = rand () % buffer_size;} printf ("randomly generated array:"); output (A, buffer_size); buildmaxheap (A, buffer_size ); printf ("the largest heap created is:"); output (A, buffer_size); System ("pause"); Return 0 ;}