Algorithm Ch6 Heapsort

Source: Internet
Author: User

Heap sorting uses a heap of this data structure to sort, the (binary) heap data structure is an array object, which can be considered as a complete two-fork tree, each node of the tree corresponds to the worthy element that holds the node in the array. The maximum heap is used for the sorting algorithm design, the largest heap is the parent (i) > Leftchild (i) and the parent (i) > Rightchild (i), first using the iterative method to build the heap.

voidMaxheapify (int(AnintNodeintiheapsize) {    intIINDEXL =Left (node); intIINDEXR =Right (node); intIlargest =0; if(Iindexl <= iheapsize && A[iindexl] >A[node]) {Ilargest=Iindexl; }    Elseilargest=node; if(Iindexr <= iheapsize && A[IINDEXR] >A[ilargest]) {Ilargest=Iindexr; }    if(Ilargest! =node)        {Swap (A[ilargest], A[node]);    Maxheapify (A, ilargest, iheapsize); }    }voidBuildheap (int*a,int&iheapsize) {    intIsize =iheapsize;  for(intILoop = isize/2; ILoop! =0; --ILoop)    {Maxheapify (A, iLoop, iheapsize); }}

The above code can establish a maximum heap, in which the elements in the a[n/2+1. N] are leaf nodes of a tree, and can be thought of as a heap with only one element, so you only need to call the other nodes in the tree with Builheap maxheapify
To build the largest heap.

Next is the sort, because the largest element in A[1] (in order to avoid the node to calculate the trouble, the sequence number starts from 1), can be exchanged with a[n], in order to Bao the maximum pair of properties call Maxheapify (A, 1, iheapsize) to maintain the maximum heap properties, and then repeat the process, The size of the heap has been reduced from n-1 to 2. The sorting section is as follows

void Heapsort (int &iheapsize) {    buildheap (A, iheapsize);    for (1;--ILoop) {swap (a[111, iheapsize);}
}

Algorithm Ch6 Heapsort

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.