liveBook · Manning

Sorted list

As explained in Fabulous Adventures in Data Structures and Algorithms

A sorted word list is a word collection stored in lexicographic order for ordered searching and prefix matching.

A sorted list stores words in lexicographic order so ordered searching can use binary search. It is a straightforward choice when the collection can be sorted ahead of time, supporting exact lookup and prefix matching with reasonable performance. section 5.1.2 section 5.0

The two core operations work as follows:

  • Contains calls binary search and treats a nonnegative result as an exact match. section 5.1.2
  • StartsWith binary-searches for the prefix, converts a negative insertion result with bitwise complement, then scans forward until the prefix no longer matches. section 5.1.2
  • Exact lookup costs O(m log n), where n is the list size and m is the typical word length; prefix lookup adds O(m) work for every matching candidate. section 5.1.2
Listing 5.1 A sorted word list
class SortedWordList : IWords
{
    private List<string> words;
    public SortedWordList(List<string> words) #1
    {
        this.words = words;
    }
    public bool Contains(string word) => words.BinarySearch(word) >= 0; #2
    public IEnumerable<string> StartsWith(string prefix)
    {
        int i = words.BinarySearch(prefix);
        if (i < 0)
            i = ~i; #3
        for (; i < words.Count; i += 1)
        {
            string w = words[i];
            if (!w.StartsWith(prefix)) #4
                yield break;
            yield return w;
        }
    }
    public IEnumerator<string> GetEnumerator() => words.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

A compact C# implementation exposes the sorted-list invariant, BinarySearch result handling, lazy prefix enumeration, and stopping condition. section 5.1.2

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Explains C# implementation details and derives O(m log n) lookup cost, including the additional scan cost of prefix matches.
Examples
Uses typing completion, word-game moves, and Scrabble bingo generation as motivating word-list searches.
What it assumes
Assumes a pre-sorted word collection and familiarity with C# lists, string comparison, and binary-search results.
What you can do after
Build it from scratch with C# List<string>, BinarySearch, insertion-point handling, and lazy prefix enumeration.
How it connects
Compares with hash sets, tries, Directed Acyclic Word Graphs, and finite state machines.

Also explained in

Compare how 3 books explain sorted list →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.