Programming Search⌘K

Conceptcore

Ordered map

Also called sorted map, tree map, sorted dictionary, navigable map, TreeMap, BTreeMap, SortedDictionary, SortedList, std::map, SortedMap, NavigableMap.

An ordered map keeps its keys sorted. It finds a key in logarithmic time, and it also gives the smallest key, the next key after a value and all keys in a range.

Applies to
core-languages

Idea

A map answers one question: what is the value for this key? An ordered map also knows the order of its keys. It can give the smallest key and the largest key, the closest key below or above a value that is not in the map, and all keys between two values. A program uses an ordered map for a timeline of events, a price list, a leaderboard or any data that it reads in key order.

Wikipedia describes the main kind: "The order of enumeration is always deterministic for a given set of keys by sorting. This is the case for tree-based implementations, one representative being the std::map (a tree map) container of C++"1. Python has no ordered map in its standard library, so the example below builds a small one from a dict and a sorted list of keys.

import bisect

# An ordered map keeps its keys sorted. Python has no such type, so this one
# keeps a dict for the values and a sorted list for the keys.
prices = {}
keys = []


def put(k, v):
    if k not in prices:
        bisect.insort(keys, k)
    prices[k] = v


for k, v in [(30, "c"), (10, "a"), (50, "e"), (20, "b"), (40, "d")]:
    put(k, v)
print(keys)

# Floor and ceiling: the largest key <= 35 and the smallest key >= 35.
i = bisect.bisect_right(keys, 35)
j = bisect.bisect_left(keys, 35)
print(keys[i - 1], keys[j])

# A range query: all keys from 20 up to but not including 45.
lo, hi = bisect.bisect_left(keys, 20), bisect.bisect_left(keys, 45)
print([(k, prices[k]) for k in keys[lo:hi]])
print(keys[0], keys[-1])
Output
[10, 20, 30, 40, 50]
30 40
[(20, 'b'), (30, 'c'), (40, 'd')]
10 50

The keys go in as 30, 10, 50, 20, 40 and come out sorted. The key 35 is not in the map, but its floor is 30 and its ceiling is 40. A hash map cannot answer these questions without a look at every key.

How it works

A tree or a sorted array. Most ordered maps are balanced search trees. Java TreeMap is "A Red-Black tree based NavigableMap implementation"2, and for C++ std::map, "Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as Red–black trees"3. Rust uses a B-tree, where each node holds an array of keys: "B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing the amount of work performed in a search"4. A sorted array of keys with a binary search is also an ordered map. It is small and fast to search, but an insert moves all later keys. C# has both: SortedDictionary is a tree and SortedList is two sorted arrays5.

Order, not hash. An ordered map compares keys with an order, not with a hash code. Rust says "keys must be of a type that implements the Ord trait, such that two keys can always be compared to determine their Ordering"4. Two keys are the same key when neither is less than the other. For C++, "two objects a and b are considered equivalent (not unique) if neither compares less than the other: !comp(a, b) && !comp(b, a)"3. So a comparator that ignores case makes apple and APPLE one key. Java warns that the order "must be consistent with equals if this sorted map is to correctly implement the Map interface"2.

Navigation. The extra operations of an ordered map find keys near a value. Java NavigableMap is "A SortedMap extended with navigation methods returning the closest matches for given search targets"6: lowerKey, floorKey, ceilingKey and higherKey return the keys "less than, less than or equal, greater than or equal, and greater than"6 a value. C++ has lower_bound and upper_bound, and Rust has range with a start and an end. Each of these takes logarithmic time, because the search goes down one path of the tree.

Tree map or hash map. A hash map is faster on average for a single lookup. A tree map has a better worst case and keeps order. Wikipedia: "The worst-case performance of self-balancing binary search trees is significantly better than that of a hash table, with a time complexity in big O notation of O(log n)"1, and "like all binary search trees, self-balancing binary search trees keep their elements in order"1. Choose a tree map when the program needs order or ranges, and a hash table when it only looks up single keys.

In languages

LanguageVerdictNote
PythonIdiom
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptIdiom
TypeScriptIdiomTypeScript has no sorted map. The JavaScript idioms apply, a Map with entries sorted on demand or a sorted array of keys with a binary search. No example file exists.
GoIdiom
RustStandard library
KotlinStandard librarySortedMapOf makes a java.util.TreeMap, and toSortedMap copies a map into one. The NavigableMap methods of Java, such as floorKey and subMap, work on it. No example file exists because kotlinc is not installed.
SQLNativeA table with an index on the key keeps the keys in order, usually in a B-tree. ORDER BY gives the order, and WHERE key BETWEEN a AND b or key >= a ORDER BY key LIMIT 1 gives ranges and ceilings.
BashIdiomBash has no sorted map. A program sorts the keys of an associative array with printf and sort, and loops over the result. No example file exists.
PowerShellStandard libraryPowerShell uses the .NET classes SortedDictionary and SortedList, for example [System.Collections.Generic.SortedDictionary[int,string]]::new(). No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and has no data structures.
CSSDoes not applyCSS has no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no maps.
Language Verdict Mechanism
Python idiom no sorted map in the standard library; sorted(d), or a sorted list of keys with bisect
JavaScript idiom no sorted map; sort the entries of a Map, or keep a sorted array of keys
TypeScript idiom the JavaScript idioms
Java stdlib TreeMap with NavigableMap: floorKey, ceilingKey, subMap, headMap, tailMap
Kotlin stdlib sortedMapOf and toSortedMap, which make a java.util.TreeMap
C# stdlib SortedDictionary<TKey,TValue> (a tree) and SortedList<TKey,TValue> (sorted arrays)
Go idiom no ordered map; slices.Sorted(maps.Keys(m)) and slices.BinarySearch
Rust stdlib BTreeMap<K, V> with range, first_key_value, last_key_value, split_off
C idiom a sorted array with qsort and bsearch; POSIX tsearch for a binary tree
C++ stdlib std::map with lower_bound, upper_bound and equal_range; std::flat_map in C++23
Bash idiom sort the keys of an associative array with sort
PowerShell stdlib the .NET SortedDictionary and SortedList
SQL native an index on the key column, usually a B-tree; ORDER BY and BETWEEN
Regex n/a patterns match text and have no maps
HTML n/a markup with no data structures
CSS n/a style rules with no data structures

C# documents the choice between its two types. "The SortedDictionary<TKey,TValue> generic class is a binary search tree with O(log n) retrieval"5. Then: "SortedList<TKey,TValue> uses less memory than SortedDictionary<TKey,TValue>. SortedDictionary<TKey,TValue> has faster insertion and removal operations for unsorted data: O(log n) as opposed to O(n) for SortedList<TKey,TValue>"5.

Python, JavaScript and Go have no ordered map. A program sorts the keys when it needs the order, or it keeps a sorted list of keys next to a hash map. Python's bisect module helps with the list: it gives "support for maintaining a list in sorted order without having to sort the list after each insertion"7.

The example files show these forms. Python sorts the items of a dict by key and by value, uses bisect for ceilings and ranges, and shows that keys of mixed types cannot be sorted. JavaScript shows that the default sort compares strings, and that an object puts integer keys first. Java uses TreeMap with floor and ceiling, its range views, and a null key that throws. C# compares SortedDictionary and SortedList. Go and C keep sorted keys and use binary search. Rust uses BTreeMap::range with bounds and split_off. C++ uses lower_bound, upper_bound, a range erase and a comparator that ignores case.

PythonGitHub
import bisect

# A dict keeps insertion order, not key order. sorted() gives the key order once.
d = {"pear": 1, "apple": 3, "fig": 2}
print(list(d), sorted(d), [v for _, v in sorted(d.items())])

# Sort by value instead of by key.
print(sorted(d.items(), key=lambda kv: kv[1]))

# A sorted list of keys with bisect gives floor, ceiling and ranges in log time.
keys = sorted([50, 10, 40, 20, 30])
print(bisect.bisect_left(keys, 25), keys[bisect.bisect_left(keys, 25)])
print(keys[bisect.bisect_left(keys, 15):bisect.bisect_right(keys, 40)])

# A key past the end has no ceiling: the index is len(keys).
print(bisect.bisect_left(keys, 99) == len(keys))

# insort keeps the list sorted, but each insert moves items, so it is linear.
bisect.insort(keys, 35)
print(keys)

# Keys must be comparable with each other. Mixed types fail.
try:
    sorted([1, "a"])
except TypeError as e:
    print(type(e).__name__)
Output
['pear', 'apple', 'fig'] ['apple', 'fig', 'pear'] [3, 2, 1]
[('pear', 1), ('fig', 2), ('apple', 3)]
2 30
[20, 30, 40]
True
[10, 20, 30, 35, 40, 50]
TypeError
  • Verdict: idiom. Python has no sorted map in the standard library. sorted(d) gives the keys in order once, and a sorted list of keys with the bisect module gives floor, ceiling and ranges in logarithmic time. insort keeps the list sorted, but each insert moves items. The third-party package sortedcontainers has SortedDict.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
#include <map>
#include <string>

// A comparator that ignores case. Keys that compare equivalent are one key.
struct NoCase {
    bool operator()(const std::string& a, const std::string& b) const {
        return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), [](unsigned char x, unsigned char y) {
            return std::tolower(x) < std::tolower(y);
        });
    }
};

int main() {
    // std::map keeps its keys sorted, usually in a red-black tree.
    std::map<int, std::string> m{{30, "c"}, {10, "a"}, {50, "e"}, {20, "b"}, {40, "d"}};
    for (const auto& [k, v] : m) std::cout << k << "=" << v << (k == 50 ? "\n" : " ");
    std::cout << m.begin()->first << " " << m.rbegin()->first << "\n";

    // lower_bound gives the first key >= x, and upper_bound the first key > x.
    auto ceil = m.lower_bound(35);
    auto floor = std::prev(m.upper_bound(35));
    std::cout << floor->first << " " << ceil->first << "\n";
    std::cout << (m.upper_bound(5) == m.begin()) << " " << (m.lower_bound(99) == m.end()) << "\n";

    // A range of keys is a pair of iterators. erase can remove the whole range.
    for (auto it = m.lower_bound(20); it != m.lower_bound(45); ++it) std::cout << it->first << ",";
    std::cout << " end\n";
    m.erase(m.begin(), m.lower_bound(30));
    std::cout << m.size() << " " << m.begin()->first << "\n";

    // A custom order: "Apple" and "APPLE" are equivalent, so the map keeps one key.
    std::map<std::string, int, NoCase> ci;
    ci["Apple"] = 1;
    ci["APPLE"] = 2;
    std::cout << ci.size() << " " << ci.begin()->first << "=" << ci.begin()->second << "\n";
}
Output
10=a 20=b 30=c 40=d 50=e
10 50
30 40
1 1
20,30,40, end
3 30
1 Apple=2
  • Verdict: stdlib. std::map keeps its keys sorted, usually in a red-black tree. lower_bound and upper_bound give ceiling and floor, a range is a pair of iterators, and erase removes a range. A comparator that ignores case makes Apple and APPLE equivalent, so the map keeps one key.
JavaGitHub
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    // A TreeMap keeps its keys sorted, whatever the order of the puts.
    NavigableMap<Integer, String> m = new TreeMap<>();
    m.put(30, "c");
    m.put(10, "a");
    m.put(50, "e");
    m.put(20, "b");
    m.put(40, "d");
    System.out.println(m);

    // The first and last keys, and the closest keys to a value that is not there.
    System.out.println(m.firstKey() + " " + m.lastKey());
    System.out.println(m.floorKey(35) + " " + m.ceilingKey(35) + " " + m.lowerKey(30) + " " + m.higherKey(30));
    System.out.println(m.floorKey(5));

    // Views of a range. A view is not a copy: a change shows in both.
    System.out.println(m.subMap(20, true, 45, false) + " " + m.headMap(30) + " " + m.tailMap(40));
    m.headMap(20).clear();
    System.out.println(m + " " + m.descendingMap());

    // pollFirstEntry removes and returns the smallest entry.
    Map.Entry<Integer, String> e = m.pollFirstEntry();
    System.out.println(e.getKey() + "=" + e.getValue() + " " + m.size());

    // A comparator that ignores case makes "a" and "A" one key.
    TreeMap<String, Integer> ci = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    ci.put("apple", 1);
    ci.put("APPLE", 2);
    System.out.println(ci + " " + ci.size());

    // A null key throws, because the map must compare it.
    try {
      m.put(null, "x");
    } catch (NullPointerException ex) {
      System.out.println("NullPointerException");
    }
  }
}
Output
{10=a, 20=b, 30=c, 40=d, 50=e}
10 50
30 40 20 40
null
{20=b, 30=c, 40=d} {10=a, 20=b} {40=d, 50=e}
{20=b, 30=c, 40=d, 50=e} {50=e, 40=d, 30=c, 20=b}
20=b 3
{apple=2} 1
NullPointerException
  • Verdict: stdlib. TreeMap is a red-black tree that implements NavigableMap: firstKey, floorKey, ceilingKey, lowerKey and higherKey, and the views subMap, headMap, tailMap and descendingMap. A change to a view changes the map. A case-insensitive comparator makes apple and APPLE one key. A null key throws.
#include <stdio.h>
#include <stdlib.h>

/* C has no ordered map. A sorted array of pairs with binary search is a simple one. */
typedef struct {
    int key;
    const char *value;
} pair;

static int cmp(const void *a, const void *b) {
    int x = ((const pair *)a)->key, y = ((const pair *)b)->key;
    return (x > y) - (x < y); /* not x - y, which can overflow */
}

/* The index of the first pair with key >= k, or n if there is none. */
static size_t lower_bound(const pair *p, size_t n, int k) {
    size_t lo = 0, hi = n;
    while (lo < hi) {
        size_t mid = lo + (hi - lo) / 2;
        if (p[mid].key < k) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

int main(void) {
    pair m[] = {{30, "c"}, {10, "a"}, {50, "e"}, {20, "b"}, {40, "d"}};
    size_t n = sizeof m / sizeof m[0];
    qsort(m, n, sizeof m[0], cmp);
    for (size_t i = 0; i < n; i++) printf("%d=%s%s", m[i].key, m[i].value, i + 1 < n ? " " : "\n");

    /* bsearch finds an exact key. */
    pair want = {40, NULL};
    pair *hit = bsearch(&want, m, n, sizeof m[0], cmp);
    printf("%s\n", hit ? hit->value : "missing");

    /* Floor and ceiling of 35. */
    size_t i = lower_bound(m, n, 35);
    printf("%d %d\n", m[i - 1].key, m[i].key);

    /* A range: the keys from 20 up to but not including 45. */
    for (size_t j = lower_bound(m, n, 20); j < lower_bound(m, n, 45); j++) printf("%d ", m[j].key);
    printf("| no ceiling for 99: %d\n", lower_bound(m, n, 99) == n);
    return 0;
}
Output
10=a 20=b 30=c 40=d 50=e
d
30 40
20 30 40 | no ceiling for 99: 1
  • Verdict: idiom. C has no ordered map. A sorted array of pairs with qsort and bsearch, and a hand-written lower bound, gives exact lookup, floor, ceiling and ranges. Inserts are linear. POSIX tsearch gives a binary tree.
using System;
using System.Collections.Generic;
using System.Linq;

// SortedDictionary is a binary search tree: inserts and removals take log time.
var d = new SortedDictionary<int, string> { [30] = "c", [10] = "a", [50] = "e", [20] = "b", [40] = "d" };
Console.WriteLine(string.Join(" ", d.Keys));
Console.WriteLine($"{d.First().Key} {d.Last().Key}");

// SortedList keeps two sorted arrays, so it can index by position.
var list = new SortedList<int, string>(d);
Console.WriteLine($"{list.Keys[0]} {list.Values[2]} {list.IndexOfKey(40)} {list.IndexOfKey(35)}");

// A floor search with the keys of a SortedList and a binary search.
var keys = list.Keys;
int i = BinarySearchFloor(keys, 35);
Console.WriteLine(i >= 0 ? keys[i] : -1);

// A range: SortedSet has GetViewBetween, and the maps need a filter.
Console.WriteLine(string.Join(" ", d.Where(p => p.Key >= 20 && p.Key < 45).Select(p => p.Value)));

// A comparer decides the order and which keys are the same.
var ci = new SortedDictionary<string, int>(StringComparer.OrdinalIgnoreCase) { ["apple"] = 1 };
ci["APPLE"] = 2;
Console.WriteLine($"{ci.Count} {ci["Apple"]}");

static int BinarySearchFloor(IList<int> ks, int x)
{
    int lo = 0, hi = ks.Count;
    while (lo < hi)
    {
        int mid = (lo + hi) / 2;
        if (ks[mid] <= x) lo = mid + 1;
        else hi = mid;
    }
    return lo - 1;
}
Output
10 20 30 40 50
10 50
10 c 3 -1
30
b c d
1 2
  • Verdict: stdlib. SortedDictionary is a binary search tree, and SortedList keeps two sorted arrays, so it can index by position and IndexOfKey gives a position or -1. Neither has a floor method, so the example searches the keys of a SortedList. A comparer sets the order and which keys are the same.
JavaScriptGitHub
// JavaScript has no ordered map. A Map keeps insertion order, not key order.
const m = new Map([[30, "c"], [10, "a"], [20, "b"]]);
console.log([...m.keys()]);

// The default sort compares strings, so 10 comes before 9.
console.log([10, 9, 1].sort(), [10, 9, 1].sort((a, b) => a - b));

// Sort the entries to get the key order. This copies the map each time.
const sorted = new Map([...m].sort((a, b) => a[0] - b[0]));
console.log([...sorted.keys()]);

// Floor: the largest key <= 25, with a binary search on a sorted key array.
const keys = [...sorted.keys()];
function floor(ks, x) {
  let lo = 0, hi = ks.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (ks[mid] <= x) lo = mid + 1;
    else hi = mid;
  }
  return lo > 0 ? ks[lo - 1] : undefined;
}
console.log(floor(keys, 25), floor(keys, 5));

// Strings in an object: integer-like keys come first in numeric order, then the others in insertion order.
const o = { b: 1, 10: 2, a: 3, 2: 4 };
console.log(Object.keys(o));
Output
[ 30, 10, 20 ]
[ 1, 10, 9 ] [ 1, 9, 10 ]
[ 10, 20, 30 ]
20 undefined
[ '2', '10', 'b', 'a' ]
  • Verdict: idiom. JavaScript has no sorted map. A Map keeps insertion order, so a program sorts its entries into a new Map or an array. The default sort compares strings, so a number sort needs a compare function. A floor search is a hand-written binary search.
package main

import (
	"fmt"
	"maps"
	"slices"
	"sort"
)

func main() {
	// Go has no ordered map. Sort the keys of a map when the order matters.
	m := map[int]string{30: "c", 10: "a", 50: "e", 20: "b", 40: "d"}
	keys := slices.Sorted(maps.Keys(m))
	fmt.Println(keys)
	for _, k := range keys[:2] {
		fmt.Printf("%d=%s\n", k, m[k])
	}

	// Floor and ceiling with a binary search on the sorted keys.
	i := sort.SearchInts(keys, 35) // the first index with keys[i] >= 35
	fmt.Println(keys[i-1], keys[i])

	// BinarySearch also says whether the key is there.
	j, found := slices.BinarySearch(keys, 40)
	fmt.Println(j, found)

	// A range query: the keys from 20 up to but not including 45.
	lo, _ := slices.BinarySearch(keys, 20)
	hi, _ := slices.BinarySearch(keys, 45)
	fmt.Println(keys[lo:hi])

	// An insert into the sorted keys must keep them sorted, and it moves the later keys.
	k := 35
	p, _ := slices.BinarySearch(keys, k)
	keys = slices.Insert(keys, p, k)
	m[k] = "x"
	fmt.Println(keys)
}
Output
[10 20 30 40 50]
10=a
20=b
30 40
3 true
[20 30 40]
[10 20 30 35 40 50]
  • Verdict: idiom. Go has no ordered map. slices.Sorted(maps.Keys(m)) gives the keys in order, and sort.SearchInts and slices.BinarySearch give floor, ceiling and ranges. slices.Insert keeps the keys sorted, but it moves the later keys.
RustGitHub
use std::collections::BTreeMap;
use std::ops::Bound::{Excluded, Included, Unbounded};

fn main() {
    // A BTreeMap keeps its keys sorted.
    let mut m = BTreeMap::new();
    for (k, v) in [(30, "c"), (10, "a"), (50, "e"), (20, "b"), (40, "d")] {
        m.insert(k, v);
    }
    println!("{:?}", m);
    println!("{:?} {:?}", m.first_key_value(), m.last_key_value());

    // Floor and ceiling: a range and one step from the right end or the left end.
    let floor = m.range(..=35).next_back();
    let ceiling = m.range(35..).next();
    println!("{:?} {:?}", floor, ceiling);
    println!("{:?}", m.range(..5).next_back());

    // A range of keys, with each bound included or excluded.
    let part: Vec<_> = m.range(20..45).map(|(k, _)| *k).collect();
    println!("{:?}", part);
    let open: Vec<_> = m.range((Excluded(20), Unbounded)).map(|(k, _)| *k).collect();
    let closed: Vec<_> = m.range((Included(20), Included(40))).map(|(k, _)| *k).collect();
    println!("{:?} {:?}", open, closed);

    // pop_first removes the smallest entry, and split_off cuts the map in two.
    println!("{:?}", m.pop_first());
    let high = m.split_off(&40);
    println!("{:?} {:?}", m, high);

    // Keys need Ord. f64 has no total order because of NaN, so BTreeMap<f64, _> does not compile.
    // An integer key, or a wrapper type with a total order, is the usual fix.
    let mut by_cents: BTreeMap<i64, &str> = BTreeMap::new();
    by_cents.insert(199, "tea");
    by_cents.insert(99, "gum");
    println!("{:?}", by_cents);
}
Output
{10: "a", 20: "b", 30: "c", 40: "d", 50: "e"}
Some((10, "a")) Some((50, "e"))
Some((30, "c")) Some((40, "d"))
None
[20, 30, 40]
[30, 40, 50] [20, 30, 40]
Some((10, "a"))
{20: "b", 30: "c"} {40: "d", 50: "e"}
{99: "gum", 199: "tea"}
  • Verdict: stdlib. BTreeMap keeps its keys sorted. first_key_value and last_key_value give the ends, range with next and next_back gives floor and ceiling, and Bound sets each end of a range. pop_first and split_off change the map. Keys need Ord, so f64 is not a key.
  • Sorted sets. A sorted set is an ordered map with no values: Java TreeSet, Rust BTreeSet, C# SortedSet and C++ std::set. See set.
  • Insertion order. An ordered map keeps the order of the keys. A map that keeps the order in which the keys were added is a different thing. Python dict, Java LinkedHashMap and JavaScript Map keep insertion order. See insertion-ordered map.
  • Range views. Java subMap, headMap and tailMap return views, not copies. A change to the view changes the map. Rust range and C++ iterator pairs also refer to the map and do not copy it.
  • Flat maps. C++23 std::flat_map and C# SortedList keep the keys in a sorted array. They use less memory and loop faster, but inserts are linear.
  • Concurrent sorted maps. Java ConcurrentSkipListMap is a sorted map that many threads can change at the same time. It uses a skip list instead of a tree.
  • Multimaps. C++ std::multimap is an ordered map that allows the same key more than once. See multimap.

Pitfalls

  • An order that disagrees with equality. A comparator that ignores case, or that compares only one field, makes two different keys into one key. The second put replaces the first value. Java says the result "must be consistent with equals"2, and the C++ map keeps one key for each class of equivalent keys.
  • Keys that change. The tree puts a key in a place by its order at the time of the insert. If the key changes so that its order changes, the map cannot find it. Rust calls this "a logic error for a key to be modified in such a way that the key’s ordering relative to any other key, as determined by the Ord trait, changes while it is in the map"4.
  • Floating-point keys. NaN has no place in an order. Rust does not let f64 be a key of a BTreeMap. In other languages, a NaN key can break the order of the tree. Use integers, such as cents instead of dollars, or a wrapper with a total order.
  • String order. The order of strings depends on the comparer. JavaScript sorts numbers as strings by default, so [10, 9, 1].sort() gives [1, 10, 9]. C# and Java can sort with culture rules that differ between machines. Give an explicit comparer, such as StringComparer.Ordinal.
  • Floor at the edge. A key below the smallest key has no floor, and a key above the largest has no ceiling. Java returns null, Rust returns None, and C++ returns end() or needs a check before std::prev. A program that does not check reads past the end.
  • A null key. Java TreeMap must compare each key, so put(null, v) throws NullPointerException with the natural order.
  • Linear inserts. A sorted array, as in SortedList or a Python list with insort, moves the later keys on each insert. For many inserts in random order, use a tree.

Cost

Operation Balanced tree (TreeMap, std::map, BTreeMap) Sorted array (SortedList, bisect) Hash map, then sort
lookup logarithmic logarithmic constant on average
insert or remove logarithmic linear constant on average
smallest or largest key logarithmic (constant in some) constant linear
floor or ceiling logarithmic logarithmic linear
range of k keys logarithmic + k logarithmic + k n log n for the sort
loop in key order linear linear n log n for the sort
memory the pairs and two or more links for each node the pairs the pairs and empty slots

Java TreeMap gives "guaranteed log(n) time cost for the containsKey, get, put and remove operations"2. A tree has a pointer for each child and visits nodes that are far apart in memory, so a lookup is slower than a lookup in a hash map of the same size. A B-tree keeps many keys in each node, which makes better use of the processor cache.

History

The balanced search trees came first in the 1960s and 1970s: the AVL tree in 1962, the B-tree in 1970 and the red-black tree in 1978. Java added TreeMap in 1998 with the Collections Framework, and Java 6 added NavigableMap. C++ had std::map in the first standard library in 1998. Rust chose a B-tree for its BTreeMap, and C++23 added std::flat_map, a map on sorted arrays. Python, JavaScript and Go have no ordered map in the standard library. In Python, the third-party package sortedcontainers fills the gap.

References

  1. Associative array, Wikipedia, Self-balancing binary search trees; Comparison; Ordered dictionary
  2. Class TreeMap, Java SE 25 API, Description
  3. std::map, cppreference.com, Description
  4. Struct BTreeMap, The Rust Standard Library, Description; range
  5. SortedDictionary<TKey,TValue> class, .NET API reference, Remarks
  6. Interface NavigableMap, Java SE 25 API, Description
  7. bisect, Array bisection algorithm, The Python Standard Library, Introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4ZZDHS/text.yaml