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