Algo-Sim › Heaps & Priority Queues
Heap Sort (Build Heap + Sift Down)
Medium · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input
Build a max-heap in O(n) by sifting down from the last parent, then swap the max to the end and sift down again, n times.
Problem
Sort an integer array in ascending order in O(n log n) time using O(1) extra space (LeetCode’s Sort an Array, solved with heap sort). Show how a max-heap is built inside the array and then emptied from the back.
Constraints
- 1 ≤ nums.length ≤ 5 · 10⁴
- -5 · 10⁴ ≤ nums[i] ≤ 5 · 10⁴
- No built-in sort
Edge cases to test
- Already sorted
- All equal
- One element
Follow-up questions
- Why is building the heap O(n), not O(n log n)?
- Most nodes are near the leaves and sift down only a little; the sum of heights is O(n).
- Is heap sort stable?
- No: swapping the root to the end can reorder equal keys. It is in place with O(n log n) worst case, unlike quicksort.
Solution
Java
public int[] sortArray(int[] a) {
int n = a.length;
// Build: sift down every parent, last one first. O(n) in total.
for (int i = n / 2 - 1; i >= 0; i--) siftDown(a, i, n);
for (int end = n - 1; end > 0; end--) {
swap(a, 0, end);
siftDown(a, 0, end);
}
return a;
}
private void siftDown(int[] a, int i, int size) {
while (2 * i + 1 < size) {
int child = 2 * i + 1;
if (child + 1 < size && a[child + 1] > a[child]) child++;
if (a[i] >= a[child]) return;
swap(a, i, child);
i = child;
}
}
private void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}Python
def sort_array(a):
n = len(a)
# Build: sift down every parent, last one first. O(n) in total.
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
return a
def sift_down(a, i, size):
while 2 * i + 1 < size:
child = 2 * i + 1
if child + 1 < size and a[child + 1] > a[child]:
child += 1
if a[i] >= a[child]:
return
a[i], a[child] = a[child], a[i]
i = childC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> sortArray(vector<int> &a) {
int n = int(a.size());
// Build: sift down every parent, last one first. O(n) in total.
for (int i = n / 2 - 1; i >= 0; i--)
siftDown(a, i, n);
for (int end = n - 1; end > 0; end--) {
swap(a, 0, end);
siftDown(a, 0, end);
}
return a;
}
void siftDown(vector<int> &a, int i, int size) {
while (2 * i + 1 < size) {
int child = 2 * i + 1;
if (child + 1 < size && a[child + 1] > a[child])
child++;
if (a[i] >= a[child])
return;
swap(a, i, child);
i = child;
}
}
void swap(vector<int> &a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
};
More Heaps & Priority Queues problems
- Kth Largest Element in an Array (Medium)
- Kth Largest Element in a Stream (Easy)
- Merge K Sorted Lists (Hard)
- Find Median from Data Stream (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Last Stone Weight (Easy)
- K Closest Points to Origin (Medium)
- Top K Frequent Words (Medium)
- Reorganize String (Medium)
- IPO (Hard)