1 template<typename T>
2 void percolatedown(T a[], int n, int i)
3 {
4 T tm = a[i];
5 int child = i<<1;
6 for (; child <= n-1; i=child, child=(child<<1)) {
7 //choose the little child
8 if (child!= n-1 && a[child] > a[child+1])
9 child++;
10 if (tm > a[child])
11 a[i] = a[child]; // move the i = child, child = (child<<1) to the for loop
12 else
13 break;
14 }
15 a[i] = tm;
16 }
17
18 template<typename T>
19 void heapsort(T a[], int n)
20 {
21 for (int i=n/2-1; i>=0; --i) // do operation at the rightest leaf root
22 percolatedown(a,n,i);
23 for (int j=n-1; j>=0; --j) {
24 T min = a[0];
25 a[0] = a[j]; //delete the minimal value
26 a[j] = min;
27 percolatedown(a,j,0);
28 }
29
30 reverse(a,n);
31 }
32
33 template<typename T>
34 void reverse(T a[], int n)
35 {
36 for (int i=0; i!=n/2; ++i) {
37 T tm = a[i];
38 a[i] = a[n-1-i];
39 a[n-1-i] = tm;
40 }
41 }