Sorting · O(n log n), O(1) extra
Heap sort
Build a max-heap, then move the root to the sorted tail n − 1 times.
The full explanation, derivation and practice are in the lesson Heap sort.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
namespace Bekadan.Dsa.Examples.Sorting;
/// <summary>
/// Heap sort, ascending: build a max-heap in place, then move the maximum to
/// the end n - 1 times. O(n log n) comparisons in every case, O(1) extra
/// space, not stable.
/// </summary>
public static class HeapSort
{
public static void Sort<T>(T[] items, Comparison<T> compare)
{
int n = items.Length;
for (int i = n / 2 - 1; i >= 0; i--) // indices n/2 .. n-1 are leaves
SiftDown(items, i, n, compare);
for (int end = n - 1; end > 0; end--)
{
(items[0], items[end]) = (items[end], items[0]); // the maximum goes to its final slot
SiftDown(items, 0, end, compare); // the heap is now items[0..end)
}
}
/// <summary>Moves items[i] down until it is >= both children inside items[0..size).</summary>
private static void SiftDown<T>(T[] items, int i, int size, Comparison<T> compare)
{
while (true)
{
int child = 2 * i + 1;
if (child >= size)
return; // a leaf
if (child + 1 < size && compare(items[child + 1], items[child]) > 0)
child++; // the larger child (the left one on ties)
if (compare(items[child], items[i]) <= 0)
return; // the parent is not smaller than its children
(items[i], items[child]) = (items[child], items[i]);
i = child;
}
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/HeapSort.cs
"""Heap sort, ascending.
Build a max-heap in place, then move the maximum to the end n - 1 times.
O(n log n) comparisons in every case, O(1) extra space, not stable.
"""
from collections.abc import Callable
from typing import Any
def _identity(item: Any) -> Any:
return item
def heap_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
n = len(items)
for i in range(n // 2 - 1, -1, -1): # indices n // 2 .. n - 1 are leaves
_sift_down(items, i, n, key)
for end in range(n - 1, 0, -1):
items[0], items[end] = items[end], items[0] # the maximum goes to its final slot
_sift_down(items, 0, end, key) # the heap is now items[0:end]
def _sift_down(items: list[Any], i: int, size: int, key: Callable[[Any], Any]) -> None:
"""Moves items[i] down until it is >= both children inside items[0:size]."""
while True:
child = 2 * i + 1
if child >= size:
return # a leaf
if child + 1 < size and key(items[child + 1]) > key(items[child]):
child += 1 # the larger child (the left one on ties)
if key(items[child]) <= key(items[i]):
return # the parent is not smaller than its children
items[i], items[child] = items[child], items[i]
i = child
Tested on CPython 3.14.0 · examples/python/dsa_examples/heap_sort.py
package dev.bekadan.dsa.sorting;
import java.util.Comparator;
/**
* Heap sort, ascending: build a max-heap in place, then move the maximum to
* the end n - 1 times. O(n log n) comparisons in every case, O(1) extra
* space, not stable.
*/
public final class HeapSort {
private HeapSort() {
}
public static <T> void sort(T[] items, Comparator<? super T> comparator) {
int n = items.length;
for (int i = n / 2 - 1; i >= 0; i--) { // indices n/2 .. n-1 are leaves
siftDown(items, i, n, comparator);
}
for (int end = n - 1; end > 0; end--) {
swap(items, 0, end); // the maximum goes to its final slot
siftDown(items, 0, end, comparator); // the heap is now items[0..end)
}
}
/** Moves items[i] down until it is >= both children inside items[0..size). */
private static <T> void siftDown(T[] items, int i, int size, Comparator<? super T> comparator) {
while (true) {
int child = 2 * i + 1;
if (child >= size) {
return; // a leaf
}
if (child + 1 < size && comparator.compare(items[child + 1], items[child]) > 0) {
child++; // the larger child (the left one on ties)
}
if (comparator.compare(items[child], items[i]) <= 0) {
return; // the parent is not smaller than its children
}
swap(items, i, child);
i = child;
}
}
private static <T> void swap(T[] items, int a, int b) {
T tmp = items[a];
items[a] = items[b];
items[b] = tmp;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/HeapSort.java
#pragma once
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
namespace bekadan::dsa {
// Heap sort, ascending: build a max-heap in place, then move the maximum to
// the end n - 1 times. O(n log n) comparisons in every case, O(1) extra
// space, not stable. (std::make_heap + std::sort_heap do the same.)
namespace detail {
// Moves items[i] down until it is >= both children inside items[0..size).
template <typename T, typename Less>
void sift_down_max(std::span<T> items, std::size_t i, std::size_t size, Less& less) {
while (true) {
std::size_t child = 2 * i + 1;
if (child >= size)
return; // a leaf
if (child + 1 < size && less(items[child], items[child + 1]))
++child; // the larger child (the left one on ties)
if (!less(items[i], items[child]))
return; // the parent is not smaller than its children
std::swap(items[i], items[child]);
i = child;
}
}
} // namespace detail
template <typename T, typename Less = std::less<>>
void heap_sort(std::span<T> items, Less less = {}) {
const std::size_t n = items.size();
for (std::size_t i = n / 2; i-- > 0;) // i = n/2 - 1 down to 0; indices n/2 .. n-1 are leaves
detail::sift_down_max(items, i, n, less);
for (std::size_t end = n; end-- > 1;) { // end = n - 1 down to 1
std::swap(items[0], items[end]); // the maximum goes to its final slot
detail::sift_down_max(items, 0, end, less); // the heap is now items[0..end)
}
}
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/heap_sort.hpp