Heapsort is an algorithm that sorts an array of numbers in non-decreasing order in time and space.

Tip

This problem can also be solved by Selection Sort in time and space.

Tip

This problem can also be solved by Insertion Sort in time and space.

Tip

This problem can also be solved by Bubble Sort in time and space.

Tip

This problem can also be solved by Merge Sort in time and space.

Tip

This problem can also be solved by Quicksort in time and space.

Tip

This problem can also be solved by Quickselect in time and space.

Algorithm 0

  1. Let multiset .
  2. For , set , and update to .

Using a Binary Heap to maintain yields an algorithm that solves the problem in time and space.

void heapsort(int n, std::vector<int> &a) {
	std::priority_queue q(a.begin(), a.end());
	for (int i = n - 1; i >= 0; i--) {
		a[i] = q.top();
		q.pop();
	}
}

Algorithm 1

Based on Algorithm 0, instead of building a Binary Heap explicitly, operating directly on the array yields an algorithm that solves the problem in time and space.

void heapsort(int n, std::vector<int> &a) {
	auto b = a.begin() - 1;
	for (int i = n; i > 0; i--) {
		for (int j = i, k; j << 1 <= n; j = k) {
			k = j << 1 | ((j << 1 | 1) <= n && b[j << 1 | 1] > b[j << 1]);
			if (b[j] < b[k]) {
				std::swap(b[j], b[k]);
			} else {
				break;
			}
		}
	}
	for (int i = n; i > 1; i--) {
		std::swap(b[1], b[i]);
		for (int j = 1, k; j << 1 < i; j = k) {
			k = j << 1 | ((j << 1 | 1) < i && b[j << 1 | 1] > b[j << 1]);
			if (b[j] < b[k]) {
				std::swap(b[j], b[k]);
			} else {
				break;
			}
		}
	}
}