M04 · Built-in Collections

Sorted Collections and Priority Queues

Many tasks need order, but not the same kind. Sometimes you need everything sorted once at the end; sometimes only the smallest element, again and again; sometimes the nearest key to a value while data keeps changing. Each need has a different best structure. This lesson compares them operation by operation and maps them to the built-in types of each language.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M04 Built-in Collections · 3 of 3 lessons available

You will be able to

  • Choose between sorting once, a sorted array with binary search, a balanced search tree and a heap from the operations a task needs.
  • Quote the costs of min, insert, delete, search, range and in-order iteration for each structure.
  • Use the sorted maps and sets of C#, Java and C++ (floor, ceiling and range queries), and the substitutes in Python.
  • Use each language's priority queue correctly: its default direction, its lack of decrease-key, and its unordered iteration.
  • Handle duplicates in sorted sets and multisets, and ties in priority queues.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Four ways to have order

"I need the data in order" can mean four different things, and each has a natural structure:

  1. Sorted output once, after all the data has arrived → collect in a dynamic array and sort once: O(n log n).
  2. Fast lookups, rare changes → a sorted array with binary search: O(log n) to search, O(n) to insert or delete because elements shift.
  3. Order while the data keeps changing: insert, delete, nearest key, ranges, in-order iteration → a balanced binary search tree: O(log n) per operation.
  4. Only the smallest (or largest) element, repeatedly → a heap: O(1) to peek, O(log n) to push or pop, O(n) to build from n elements.

The heap is the weakest promise and the cheapest structure. The lab above shows why: after Heapify, the array is only partially ordered (each parent ≤ its children), yet the minimum is always at the root. Pops come out sorted shows that popping repeatedly does yield sorted order, one O(log n) pop at a time, which is heap sort.

The cost table

Operation Sorted array Balanced tree (sorted map/set) Binary heap
Build from n items O(n log n) (sort) O(n log n); linear in C++ if the input is already sorted O(n) (heapify)
Find min / max O(1) O(log n) (C++ begin() is O(1)) O(1) for the one end it serves; the other end is O(n)
Insert O(n) (shift) O(log n) O(log n)
Remove min O(n) at the front, O(1) at the back O(log n) O(log n)
Search for a key O(log n) O(log n) O(n)
Remove an arbitrary key O(n) O(log n) O(n) to find it
Floor / ceiling (nearest key) O(log n) O(log n) not supported
Range [a, b] with k results O(log n + k) O(log n + k) not supported
Iterate in sorted order O(n) O(n) O(n log n) (pop everything)

The asymptotics of the heap and the tree look similar for insert and remove-min, but the heap is an array with no per-node pointers: smaller, more cache-friendly, and faster by a constant factor. Pick the tree only when you need what the heap lacks: search, arbitrary removal, nearest keys, ranges, or sorted iteration. The BST lesson shows why balance matters: an unbalanced tree degrades to O(n) per operation, which is why every library tree is self-balancing (module M20).

Sorted collections in each language

C# Python Java C++
Sorted map SortedDictionary<K,V> (tree), SortedList<K,V> (two sorted arrays) none in the standard library TreeMap<K,V> (red-black tree) std::map (typically red-black); std::flat_map (C++23, sorted arrays)
Sorted set SortedSet<T> (tree) none; bisect on a sorted list TreeSet<E> std::set; std::flat_set (C++23)
Duplicates allowed no (keep a count as the value) (your list, your rules) no std::multimap, std::multiset
Floor / ceiling GetViewBetween(lo, hi) then Min/Max bisect_left / bisect_right floorKey, ceilingKey, lowerKey, higherKey lower_bound (first ≥), upper_bound (first >)
Range view GetViewBetween slicing between two bisect positions subMap, headMap, tailMap [lower_bound(a), upper_bound(b))

Details that matter:

  • C#. SortedList stores keys and values in two arrays: lookups are O(log n), inserts are O(n) unless they arrive in sorted order, and it uses less memory than SortedDictionary. The documentation recommends it when the data is populated all at once from sorted input.
  • Python. The standard library deliberately has no sorted container. bisect.insort finds the position in O(log n) but inserting into the list is O(n), as the bisect documentation itself points out. For heavy use, a third-party sorted-container package is the usual answer; for one-off needs, sort once.
  • Java. TreeMap documents guaranteed log(n) time for containsKey, get, put and remove. It implements NavigableMap, which provides the floor, ceiling and range methods, and pollFirstEntry to remove the smallest. Ordering comes from compareTo or a Comparator, not equals (see the previous lesson).
  • C++. std::map::operator[] inserts a default value for a missing key. On a std::multiset, erase(value) removes all copies; erase(s.find(value)) removes one. The floor of x is the element before upper_bound(x), if there is one. The flat_ containers trade O(n) insertion for contiguous storage and faster iteration and lookup in practice.

Priority queues in each language

The heaps lesson explains sift up, sift down and O(n) heapify, and has the full table of APIs; the encyclopedia pages have tested examples for every operation. In short:

Type Default Push / pop / peek Notes
C# PriorityQueue<TElement,TPriority> min O(log n) / O(log n) / O(1) element and priority are separate; 4-ary heap; no decrease-key
Python heapq functions on a list min O(log n) / O(log n) / O(1) (heap[0]) heapify is O(n); nsmallest/nlargest for top k
Java PriorityQueue<E> min O(log n) / O(log n) / O(1) remove(Object) and contains are linear
C++ std::priority_queue<T> max O(log n) / O(log n) / O(1) pop() returns nothing: read top() first

Three things are true of all four:

  • Iteration is not in priority order. Enumerating the queue (or printing it) shows the internal heap array.
  • No decrease-key. To change a priority, push the element again with the new priority and skip stale entries when they come out; Dijkstra's algorithm in this lab does exactly that (Dijkstra lesson).
  • Ties are not first-in, first-out. A heap is not stable. If arrival order matters among equal priorities, compare (priority, sequence number) pairs. In Python this also stops the heap from comparing the payload objects, which might not support <.

Choosing between them

Task Structure Cost
Print a leaderboard once at the end dynamic array, sort once O(n log n)
Keep the k largest values of a stream min-heap of size k O(n log k) total, O(k) memory
Always process the most urgent job next priority queue O(log n) per job
"Which booking starts at or after 14:00?" while bookings change sorted map, ceiling query O(log n)
Count events in a time window while events arrive sorted map or set with a range query O(log n + k)
Running median two heaps (a max-heap for the lower half, a min-heap for the upper) O(log n) per insert
Lookups only, data loaded once sorted array + binary search, or a hash map if order is not needed O(log n) / expected O(1)

The top-k heap pattern collects problems that need only the heap. If you find yourself wanting contains or remove(x) on a priority queue, that is usually the sign that a sorted set (or a heap plus a hash map of "deleted" marks) fits better.

Common mistakes

  • Using a sorted collection to get the minimum when nothing else is needed: a heap is simpler and faster.
  • Sorting after every insertion: n inserts become O(n² log n). Insert into a tree or heap, or sort once at the end.
  • Iterating a priority queue and expecting sorted order.
  • Forgetting that std::priority_queue is a max-heap while C#, Python and Java default to min.
  • Expecting a sorted set to keep duplicates. Use a count map, a multiset (C++), or make keys unique with a sequence number.
  • Inconsistent comparators, which break both sorted collections and heaps.

Worked practice

1. You need the 10 smallest of 10 million numbers. Sort, or heap?

A max-heap of size 10 holding the smallest seen so far: O(n log 10) = O(n), with O(1) memory beyond the input. Python's heapq.nsmallest(10, data) does this. Sorting costs O(n log n) and, if you copy, O(n) memory.

2. Meeting rooms: given a time t, find the next meeting that starts at or after t, while meetings are added and cancelled. Which structure and which method?

A sorted map from start time to meeting. Java: ceilingEntry(t); C++: m.lower_bound(t); C#: SortedDictionary has no ceiling method, so use SortedSet of start times with GetViewBetween(t, max).Min, or a SortedList with a binary search over Keys; Python: keep a sorted list of start times and use bisect_left, accepting O(n) insertion. All tree-based options are O(log n) per operation.

3. Why is building a heap from n values O(n) but building a balanced tree O(n log n)?

Heapify only establishes the weak heap property, and most nodes are near the bottom where sifting down is cheap; the sum of heights is O(n). A search tree must be fully ordered, which amounts to sorting, and comparison sorting needs Ω(n log n) comparisons in the worst case. (A tree can be built in O(n) only if the input is already sorted.)

4. A C++ std::multiset<int> s{3, 3, 3}; you call s.erase(3). What is left?

Nothing. erase(key) removes every element equivalent to the key and returns how many it removed (3). To remove one copy, use s.erase(s.find(3)), after checking that find did not return end().

Summary

  • Sort once if you need order once; use a sorted array for lookups on static data.
  • A balanced tree keeps full order under changes: O(log n) insert, delete, search, floor, ceiling and ranges.
  • A heap keeps only the minimum (or maximum) cheap: O(1) peek, O(log n) push/pop, O(n) build, and less memory.
  • C#, Java and C++ ship sorted maps and sets; Python's standard library offers bisect and heapq instead.
  • Priority queues iterate in heap order, have no decrease-key, are not stable, and in C++ default to max.

Full implementation

The binary min-heap in four languages, each checked against one shared fixture of heapify, push, pop and peek sequences (including the exact heap array and errors on an empty heap), and 500 random operation sequences compared with PriorityQueue, heapq, java.util.PriorityQueue and std::priority_queue.

namespace Bekadan.Dsa.Examples.Heaps;
 
/// <summary>
/// Array-backed binary min-heap. Parent of i: (i - 1) / 2; children: 2i + 1, 2i + 2.
/// Push and Pop are O(log n), Peek is O(1), building from n items is O(n).
/// </summary>
public sealed class BinaryHeap<T>
{
    private readonly List<T> _items;
    private readonly Comparison<T> _compare;
 
    public BinaryHeap(Comparison<T>? compare = null) : this([], compare)
    {
    }
 
    /// <summary>Builds a heap from existing items with bottom-up heapify.</summary>
    public BinaryHeap(IEnumerable<T> items, Comparison<T>? compare = null)
    {
        _items = [.. items];
        _compare = compare ?? Comparer<T>.Default.Compare;
        for (int i = _items.Count / 2 - 1; i >= 0; i--) // indices Count/2 and up are leaves
            SiftDown(i);
    }
 
    public int Count => _items.Count;
 
    /// <summary>The heap array, index 0 first (for tests and teaching).</summary>
    public IReadOnlyList<T> Items => _items;
 
    public void Push(T value)
    {
        _items.Add(value); // the next free slot keeps the tree complete
        int i = _items.Count - 1;
        while (i > 0)
        {
            int parent = (i - 1) / 2;
            if (_compare(_items[i], _items[parent]) >= 0)
                break; // not smaller than its parent: done
            (_items[i], _items[parent]) = (_items[parent], _items[i]);
            i = parent;
        }
    }
 
    public T Peek()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        return _items[0];
    }
 
    public T Pop()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        T top = _items[0];
        int last = _items.Count - 1;
        _items[0] = _items[last]; // the last element fills the hole at the root
        _items.RemoveAt(last);
        if (_items.Count > 0)
            SiftDown(0);
        return top;
    }
 
    private void SiftDown(int i)
    {
        while (true)
        {
            int child = 2 * i + 1;
            if (child >= _items.Count)
                return; // a leaf
            if (child + 1 < _items.Count && _compare(_items[child + 1], _items[child]) < 0)
                child++; // the smaller child (the left one on ties)
            if (_compare(_items[child], _items[i]) >= 0)
                return; // not larger than its children: done
            (_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/Heaps/BinaryHeap.cs

"""Array-backed binary min-heap.
 
Parent of i: (i - 1) // 2; children: 2i + 1 and 2i + 2. push and pop are
O(log n), peek is O(1), building from n items is O(n). The standard library's
heapq module offers the same operations as functions on a plain list.
"""
 
from collections.abc import Iterable
from typing import Generic, TypeVar
 
T = TypeVar("T")
 
 
class BinaryHeap(Generic[T]):
    def __init__(self, items: Iterable[T] = ()) -> None:
        """Builds a heap from existing items with bottom-up heapify."""
        self._items: list[T] = list(items)
        for i in range(len(self._items) // 2 - 1, -1, -1):  # indices len // 2 and up are leaves
            self._sift_down(i)
 
    def __len__(self) -> int:
        return len(self._items)
 
    def items(self) -> list[T]:
        """A copy of the heap array, index 0 first (for tests and teaching)."""
        return list(self._items)
 
    def push(self, value: T) -> None:
        a = self._items
        a.append(value)  # the next free slot keeps the tree complete
        i = len(a) - 1
        while i > 0:
            parent = (i - 1) // 2
            if not a[i] < a[parent]:
                break  # not smaller than its parent: done
            a[i], a[parent] = a[parent], a[i]
            i = parent
 
    def peek(self) -> T:
        if not self._items:
            raise IndexError("peek from an empty heap")
        return self._items[0]
 
    def pop(self) -> T:
        a = self._items
        if not a:
            raise IndexError("pop from an empty heap")
        top = a[0]
        last = a.pop()
        if a:
            a[0] = last  # the last element fills the hole at the root
            self._sift_down(0)
        return top
 
    def _sift_down(self, i: int) -> None:
        a = self._items
        while True:
            child = 2 * i + 1
            if child >= len(a):
                return  # a leaf
            if child + 1 < len(a) and a[child + 1] < a[child]:
                child += 1  # the smaller child (the left one on ties)
            if not a[child] < a[i]:
                return  # not larger than its children: done
            a[i], a[child] = a[child], a[i]
            i = child

Tested on CPython 3.14.0 · examples/python/dsa_examples/binary_heap.py

package dev.bekadan.dsa.heaps;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
 
/**
 * Array-backed binary min-heap (with respect to the comparator). Parent of i:
 * (i - 1) / 2; children: 2i + 1, 2i + 2. push and pop are O(log n), peek is
 * O(1), building from n items is O(n).
 */
public final class BinaryHeap<T> {
    private final List<T> items;
    private final Comparator<? super T> comparator;
 
    public BinaryHeap(Comparator<? super T> comparator) {
        this(List.of(), comparator);
    }
 
    /** Builds a heap from existing items with bottom-up heapify. */
    public BinaryHeap(Collection<? extends T> initial, Comparator<? super T> comparator) {
        this.items = new ArrayList<>(initial);
        this.comparator = comparator;
        for (int i = items.size() / 2 - 1; i >= 0; i--) { // indices size/2 and up are leaves
            siftDown(i);
        }
    }
 
    public int size() {
        return items.size();
    }
 
    /** The heap array, index 0 first (for tests and teaching). */
    public List<T> items() {
        return Collections.unmodifiableList(items);
    }
 
    public void push(T value) {
        items.add(value); // the next free slot keeps the tree complete
        int i = items.size() - 1;
        while (i > 0) {
            int parent = (i - 1) / 2;
            if (comparator.compare(items.get(i), items.get(parent)) >= 0) {
                break; // not smaller than its parent: done
            }
            Collections.swap(items, i, parent);
            i = parent;
        }
    }
 
    public T peek() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        return items.get(0);
    }
 
    public T pop() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        T top = items.get(0);
        T last = items.remove(items.size() - 1);
        if (!items.isEmpty()) {
            items.set(0, last); // the last element fills the hole at the root
            siftDown(0);
        }
        return top;
    }
 
    private void siftDown(int i) {
        while (true) {
            int child = 2 * i + 1;
            if (child >= items.size()) {
                return; // a leaf
            }
            if (child + 1 < items.size() && comparator.compare(items.get(child + 1), items.get(child)) < 0) {
                child++; // the smaller child (the left one on ties)
            }
            if (comparator.compare(items.get(child), items.get(i)) >= 0) {
                return; // not larger than its children: done
            }
            Collections.swap(items, i, child);
            i = child;
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/heaps/BinaryHeap.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// Array-backed binary min-heap (with respect to Less). Parent of i: (i - 1) / 2;
// children: 2i + 1, 2i + 2. push and pop are O(log n), top is O(1), building from
// n items is O(n). Note: std::priority_queue with std::less is a MAX-heap.
 
template <typename T, typename Less = std::less<>>
class BinaryHeap {
public:
    explicit BinaryHeap(Less less = {}) : less_(std::move(less)) {}
 
    // Builds a heap from existing items with bottom-up heapify.
    explicit BinaryHeap(std::vector<T> items, Less less = {}) : items_(std::move(items)), less_(std::move(less)) {
        for (std::size_t i = items_.size() / 2; i-- > 0;)  // i = size/2 - 1 down to 0; the rest are leaves
            sift_down(i);
    }
 
    [[nodiscard]] std::size_t size() const noexcept { return items_.size(); }
    [[nodiscard]] bool empty() const noexcept { return items_.empty(); }
 
    // The heap array, index 0 first (for tests and teaching).
    [[nodiscard]] const std::vector<T>& items() const noexcept { return items_; }
 
    void push(T value) {
        items_.push_back(std::move(value));  // the next free slot keeps the tree complete
        std::size_t i = items_.size() - 1;
        while (i > 0) {
            const std::size_t parent = (i - 1) / 2;
            if (!less_(items_[i], items_[parent]))
                break;  // not smaller than its parent: done
            std::swap(items_[i], items_[parent]);
            i = parent;
        }
    }
 
    [[nodiscard]] const T& top() const {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        return items_.front();
    }
 
    T pop() {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        T result = std::move(items_.front());
        if (items_.size() > 1)
            items_.front() = std::move(items_.back());  // the last element fills the hole at the root
        items_.pop_back();
        if (!items_.empty())
            sift_down(0);
        return result;
    }
 
private:
    void sift_down(std::size_t i) {
        while (true) {
            std::size_t child = 2 * i + 1;
            if (child >= items_.size())
                return;  // a leaf
            if (child + 1 < items_.size() && less_(items_[child + 1], items_[child]))
                ++child;  // the smaller child (the left one on ties)
            if (!less_(items_[child], items_[i]))
                return;  // not larger than its children: done
            std::swap(items_[i], items_[child]);
            i = child;
        }
    }
 
    std::vector<T> items_;
    Less less_;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/binary_heap.hpp

References