1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class HeapSort { public: void sink(int a[],int n,int k) { while (k <= n / 2) { int j = 2 * k; if (j + 1 <= n && a[j] < a[j + 1]) j++; if (a[k] < a[j]) swap(a[k], a[j]); else break; k = j; } }
void swim(int a[],int n,int k) { while (k > 1 && a[k / 2] < a[k]) { swap(a[k / 2], a[k]); k = k / 2; } }
void sort(int a[],int n) { for (int k = n / 2; k >= 1; k--) sink(a, n, k); while (n > 1) { swap(a[1], a[n]); n--; sink(a,n,1); } } };
|