1
Heap Sort
Algorithm › Sort
Build a max-heap, then repeatedly move the root (largest) to the end and re-heapify the rest. O(n log n) always, in-place, not stable.
void heapify(vector<int> &a, int n, int i) {
int largest = i, l = 2 * i + 1, r = 2 * i + 2;
if (l < n && a[l] > a[largest]) largest = l;
if (r < n && a[r] > a[largest]) largest = r;
if (largest != i) {
swap(a[i], a[largest]);
heapify(a, n, largest);
}
}
void heapSort(vector<int> &a) {
int n = a.size();
for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i); // build heap O(n)
for (int i = n - 1; i > 0; i--) {
swap(a[0], a[i]); // largest to the end
heapify(a, i, 0);
}
}