Data structure and algorithm--heap ordering

Source: Internet
Author: User

Code:

void heapsort (int a[], int n) {
int Tmp;
for (int i = N/2; I >= 0; i--)
Percdown (A, I, n);
/*build a heap; we should know that intinially we put all of the elements randomly and then
we begin to percolate the heap from the last Element (N/2) which have the child;
Notice that the elements we should percolate is always the The elements.*/

/*before The beginning of the formal heapsort, the array has been adjusted to a heap*/

for (int i = n-1; I >= 1; i++) {
TMP = A[i];
A[i] = a[0];
A[0] = TMP;
/*this Step aim at Remove the minimum element out of the Heap,it ' s important to
understand the following progress of percolating the heap would not affect this
element*/
Percdown (A, 0, i);
/*we just percolate down the first elements, which would not affect those elements which
Have been sorted*/
    }
}
Down filtering algorithm, starting from the I node adjustment, n is the total number of nodes, starting from 0, I node of the child node is 2*i+1,2*i+2
void Percdown (int a[], int i, int n)
{
int child, temp;

temp = A[i];/*remember The element which is expected to adjust*/
Child = 2 * i + 1;
while (Child < n) {
if (child + 1 < n && a[child + 1] < A[child])
child++;
/*find The smaller ensure all childs is all larger than the parent*/
if (A[child] >= temp) break;
/*if So, the position would is identified.*/
else{
A[i] = A[child];//make the smaller child become the parent node
i = child;//the child position become the new parent position
Child = 2 * i + 1;//The new left child position
}
}

A[i] = temp;
/*find the appropriate position*/
}

Data structure and algorithm--heap ordering

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.