# Implementation of C ++ heap sorting

Source: Internet
Author: User

Print? Void HeapAdjust (int a [], int s, int n) // construct heap
{
Int j, t;
While (2 * s + 1 <n) // whether the left subtree exists
{
J = 2 * s + 1;
If (j + 1) <n)
{
If (a [j] <a [j + 1]) // if the left subtree is smaller than the right subtree, you must compare the right subtree.
J ++; // increase the serial number by 1 to point to the right subtree.
}
If (a [s] <a [j]) // compare data in which s and j are serial numbers.
{
T = a [s];
A [s] = a [j];
A [j] = t;
S = j; // after the switch, the heap structure of the subnode of the node is damaged and needs to be adjusted downward.
}
Else // when the number of children is relatively large, the heap is not damaged and no adjustment is required.
Break;
}
}
Void HeapSort (int a [], int n) // heap sorting
{
Int t, I;
Int j;
// Heap creation process
For (I = n/2-1; I> = 0; I --) // build a [0, n-1] into a large root heap, determine whether the heap structure is satisfied from the first non-leaf node During Heap creation, and then adjust it.
// Output the heap top element (exchanged with the end element) of the modified heap, and re-adjusted the entire heap from the root node.
// Repeat n-1 times
For (I = n-1; I> 0; I --)
{
T = a [0]; // exchange with the I-th record (the record after I has been ordered) to output the record on the heap
A [0] = a [I];
A [I] = t;
HeapAdjust (a, 0, I); // you can change a [0] to a [I] to a heap, only the heap top is damaged, so it is adjusted down from the top of the heap.
}
}

Related Keywords:
Related Article

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.