Sub topic 13
Ordered collections in Java, C++ and Python
This chapter assumes you know basic map and set operations, Big-O notation, and binary search. It maps the ordered map and sorted set interface onto what each of the three languages gives you.
Java: TreeMap and TreeSet
Java has the most complete ordered API. TreeMap and TreeSet are red-black trees. They implement NavigableMap and NavigableSet, which add the navigation and range operations from earlier chapters.
import java.util.TreeMap;
public class Grades {
public static void main(String[] args) {
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(60, "D");
grades.put(70, "C");
grades.put(80, "B");
grades.put(90, "A");
System.out.println(grades.floorEntry(85).getValue()); // B
System.out.println(grades.ceilingKey(85)); // 90
System.out.println(grades.subMap(70, 90)); // {70=C, 80=B}
}
}subMap, headMap and tailMap return live views, not copies. Writing through a view changes the original map. Lookup, insert and delete cost O(log n).
C++: std::map and std::set
C++ offers std::map, std::set, std::multimap and std::multiset. They are usually red-black trees. Instead of floor and ceiling, you use iterators:
lower_bound(k)returns the first element with key >= k.upper_bound(k)returns the first element with key > k.begin()andstd::prev(end())give the first and last elements.
#include <iostream>
#include <iterator>
#include <map>
#include <string>
int main() {
std::map<int, std::string> grades{{60, "D"}, {70, "C"}, {80, "B"}, {90, "A"}};
// floor(85): the last entry with key <= 85
auto it = grades.upper_bound(85); // first key > 85, which is 90
if (it != grades.begin()) {
--it;
std::cout << it->second << "\n"; // B
}
// range [70, 90): iterate from lower_bound(70) up to lower_bound(90)
for (auto r = grades.lower_bound(70); r != grades.lower_bound(90); ++r) {
std::cout << r->first << "=" << r->second << " ";
}
std::cout << "\n"; // 70=C 80=B
}Ranges are pairs of iterators, so a range never allocates. Check for end() before you dereference an iterator.
Python: no built-in ordered map
The standard library has no tree-based map. A dict keeps insertion order, not sorted order. The usual approach is a sorted list with the bisect module, as shown in the sorted-array chapter.
from bisect import bisect_left, bisect_right, insort
scores = []
for s in [50, 20, 40, 20, 30]:
insort(scores, s)
lo = bisect_left(scores, 20)
hi = bisect_right(scores, 40)
print(scores[lo:hi]) # [20, 20, 30, 40]Search is O(log n), but insort is O(n) because elements shift. This is fast enough for thousands of items. For larger or write-heavy data, the third-party sortedcontainers package provides SortedDict and SortedList with good practical performance.
Comparing the three
| Feature | Java | C++ | Python |
|---|---|---|---|
| Ordered map | `TreeMap` | `std::map` | `SortedDict` (third-party) |
| Sorted set | `TreeSet` | `std::set` | `SortedList` or `bisect` on a list |
| Floor and ceiling | `floorKey`, `ceilingKey` | `lower_bound`, `upper_bound` | `bisect_left`, `bisect_right` |
| Range view | `subMap` (live view) | iterator pair | list slice (copy) |
| Custom order | `Comparator` | comparison functor | `key=` function |
Exercise
In C++, how do you find the largest key less than or equal to k in a std::map, and what must you check first?
Show answer
Call upper_bound(k) to get the first key greater than k, then step back one position with --it. Before stepping back, check that the iterator is not begin(). If it is, no key is less than or equal to k.
Exercise
Why is insort on a Python list O(n) even though it finds the position in O(log n)?
Show answer
Inserting into the middle of an array shifts every later element one slot to the right, which costs O(n). The binary search only finds where to insert.