Four ways to have order
"I need the data in order" can mean four different things, and each has a natural structure:
- Sorted output once, after all the data has arrived → collect in a dynamic array and sort once: O(n log n).
- Fast lookups, rare changes → a sorted array with binary search: O(log n) to search, O(n) to insert or delete because elements shift.
- Order while the data keeps changing: insert, delete, nearest key, ranges, in-order iteration → a balanced binary search tree: O(log n) per operation.
- 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#.
SortedListstores 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 thanSortedDictionary. 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.insortfinds the position in O(log n) but inserting into the list is O(n), as thebisectdocumentation itself points out. For heavy use, a third-party sorted-container package is the usual answer; for one-off needs, sort once. - Java.
TreeMapdocuments guaranteed log(n) time forcontainsKey,get,putandremove. It implementsNavigableMap, which provides the floor, ceiling and range methods, andpollFirstEntryto remove the smallest. Ordering comes fromcompareToor aComparator, notequals(see the previous lesson). - C++.
std::map::operator[]inserts a default value for a missing key. On astd::multiset,erase(value)removes all copies;erase(s.find(value))removes one. The floor ofxis the element beforeupper_bound(x), if there is one. Theflat_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_queueis 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
bisectandheapqinstead. - Priority queues iterate in heap order, have no decrease-key, are not stable, and in C++ default to max.