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