Chapter 6 heap sorting-"heap BUILD-MAX-HEAP" (recursive Version)

Source: Internet
Author: User

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 <1; int right = (I <1) + 1; int TMP; int largest = I; If (left <= heapsize & A [I] <A [left]) {largest = left ;} if (right <= heapsize & A [Largest] <A [right]) {largest = right;} if (I! = Largest) // if this judgment is not added, an endless loop may be generated. recursively round {TMP = A [I]; A [I] = A [Largest]; A [Largest] = TMP; maxheapify (A, largest, heapsize) ;}} void output (int * a, int Len) {int I = 1; for (I = 1; I <= Len; I ++) {printf ("% d", a [I]);} printf ("\ n");} void buildmaxheap (int *, 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]. In this way, the index of the subnode is calculated as simple. 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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.