Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Selection and equivalence classes

ProblemFind the largest elements without sorting everything, and group items into the classes of an equivalence relation
Devised byJ. W. J. Williams (1964), heaps; Bernard Galler and Michael Fischer (1964), union-find; the bounded-heap selection is folklore
AccuracyExact; results are checked against a full sort in the generator
CostSelection time and memory; equivalence classes relation tests
Read firstComparison sorting: quicksort, heapsort and Shell’s method
APIselect_m_largest, equivalence_classes

Overview

Often only part of a sorted order is wanted: the ten best scores, the hundred nearest candidates, the largest peaks of a spectrum. Sorting everything costs . Keeping the best seen so far in a small heap costs , reads the data once, and needs only memory, so it works on streams too long to hold.

Another frequent need is grouping: which files are duplicates, which words are anagrams, which measurements belong to the same object. When “belongs with” is an equivalence relation, reflexive, symmetric and transitive, the items fall into disjoint equivalence classes. If the given relation is not transitive, for example “within 2 of each other”, the library takes its transitive closure: two items are in the same class when a chain of related items joins them.

Where it is used

Often only the largest few items matter, not the whole order.

  • Top-k queries. The ten best search results, the largest peaks in a spectrum or the nearest neighbours of a point.
  • Medians and quantiles. Computed without sorting everything, in robust statistics and image filters.
  • Equivalence classes. Grouping items that are related by a symmetric, transitive relation, as in clustering duplicates and connected regions.

History

Heaps were introduced by J. W. J. Williams in 1964 for heapsort and soon became the standard priority queue. Selecting the smallest with a bounded heap appears in early textbooks on sorting and in database “top-” query processing. The exact selection algorithms are Hoare’s quickselect (1961) and the median-of-medians method of Blum, Floyd, Pratt, Rivest and Tarjan (1973). Equivalence classes were the original application of the disjoint-set forest of Bernard Galler and Michael Fischer (1964), devised for FORTRAN’s EQUIVALENCE statements. Numerical Recipes popularised a routine of the same name.

The idea

Selecting the m largest

Keep a min-heap of at most elements. Its root is the smallest of the best so far, the threshold for getting in. For each new element: if the heap is not full, add it; otherwise, if the element beats the root, replace the root. At the end, sort the survivors in descending order. Each step costs at most , and for random input most elements fail the threshold test after one comparison.

pub fn select_m_largest<T: Ord + Clone>(slice: &[T], m: usize) -> Vec<T> {
    if m == 0 {
        return Vec::new();
    }
    let mut heap: BinaryHeap<Reverse<T>> = BinaryHeap::with_capacity(m + 1);
    for item in slice {
        if heap.len() < m {
            heap.push(Reverse(item.clone()));
        } else if let Some(Reverse(min)) = heap.peek()
            && item > min {
                heap.pop();
                heap.push(Reverse(item.clone()));
            }
    }
    let mut out: Vec<T> = heap.into_iter().map(|Reverse(x)| x).collect();
    out.sort_by(|a, b| b.cmp(a));
    out
}

Table 25.2. Selecting the largest elements against sorting everything.

m largest of one millionselect_m_largestsorting everything
100.3 ms9.8 ms
10000.6 ms9.8 ms
10000016.0 ms9.8 ms

For small selection is an order of magnitude faster than sorting. As approaches it loses that advantage. The heap then does the work of a heapsort, and the standard library’s sort is faster.

Equivalence classes

Each item starts in its own class. For every pair not yet in the same class, test the relation, and if it holds, merge their classes with a union-find structure. Path halving keeps the trees shallow. At the end, items are gathered by their class representative. Classes come out in order of their first member, with members in input order.

pub fn equivalence_classes<T, F>(items: &[T], equiv: F) -> Vec<Vec<T>>
where
    T: Clone,
    F: Fn(&T, &T) -> bool,
{
    let n = items.len();
    let mut parent: Vec<usize> = (0..n).collect();

    fn find(parent: &mut [usize], mut x: usize) -> usize {
        while parent[x] != x {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        x
    }

    for i in 0..n {
        for j in (i + 1)..n {
            let (ri, rj) = (find(&mut parent, i), find(&mut parent, j));
            if ri != rj && equiv(&items[i], &items[j]) {
                // Keep the smaller index as root so classes order by first member.
                if ri < rj {
                    parent[rj] = ri;
                } else {
                    parent[ri] = rj;
                }
            }
        }
    }

    let mut index_of_root: Vec<Option<usize>> = vec![None; n];
    let mut classes: Vec<Vec<T>> = Vec::new();
    for (i, item) in items.iter().enumerate() {
        let r = find(&mut parent, i);
        match index_of_root[r] {
            Some(k) => classes[k].push(item.clone()),
            None => {
                index_of_root[r] = Some(classes.len());
                classes.push(vec![item.clone()]);
            }
        }
    }
    classes
}

Testing every pair costs relation tests:

Table 25.3. Time to form equivalence classes.

itemsclassestime
50070.4 ms
100071.3 ms
200075.3 ms

That suits relations given only as a yes/no test. When items have a canonical key, such as the sorted letters of a word or a rounded value, sorting or hashing by the key groups them in or instead.

Algorithm

Selecting the largest of elements.

  1. Start with an empty min-heap.
  2. For each element: if the heap holds fewer than elements, insert it. Otherwise compare it with the root, the smallest element kept so far; if it is larger, replace the root by it and restore the heap.
  3. Remove the heap’s contents and sort them in descending order.

The cost is at worst, and close to comparisons for random input, since most elements fail the comparison with the root.

Equivalence classes of items under a relation given as a test.

  1. Start a union-find structure with each item in its own class.
  2. For every pair : if the two are already in the same class, skip the pair (the test is not needed); otherwise apply the test, and if it holds, merge the two classes, keeping the smaller index as the root.
  3. Group the items by their root, listing the classes in order of their first member.

The number of tests is at most , and fewer when classes are large, because pairs already known to be equivalent are skipped.

Implementation

  • select_m_largest clones the selected elements (T: Ord + Clone) and returns them largest first; m = 0 gives an empty vector and all elements sorted.
  • equivalence_classes takes any closure Fn(&T, &T) -> bool, which need only be symmetric; it skips the test for pairs already joined.

In practice

//! Selecting the largest elements, and grouping items into equivalence classes.

use lib_jsl_sorting::{equivalence_classes, select_m_largest};

fn main() {
    let scores = [72, 95, 61, 88, 95, 79, 100, 54, 83];
    println!("top three scores: {:?}", select_m_largest(&scores, 3));

    // Words are equivalent when they are anagrams; classes keep their first appearance order.
    let words = ["listen", "google", "enlist", "inlets", "banana", "silent", "elgoog"];
    let sorted = |w: &&str| { let mut c: Vec<char> = w.chars().collect(); c.sort_unstable(); c };
    let anagrams = equivalence_classes(&words, |a, b| sorted(a) == sorted(b));
    println!("anagram classes: {anagrams:?}");

    // The relation need only link some pairs: classes are its transitive closure. Here numbers
    // within 2 of each other are linked, so chains of close numbers form one class.
    let readings = [1.0, 2.5, 4.0, 10.0, 11.5, 30.0];
    let clusters = equivalence_classes(&readings, |a: &f64, b: &f64| (a - b).abs() <= 2.0);
    println!("chained clusters: {clusters:?}");
}
top three scores: [100, 95, 95]
anagram classes: [["listen", "enlist", "inlets", "silent"], ["google", "elgoog"], ["banana"]]
chained clusters: [[1.0, 2.5, 4.0], [10.0, 11.5], [30.0]]

In the last line 1.0 and 4.0 are 3 apart, yet in the same class, linked through 2.5.

Strengths

  • One-pass, low-memory top- selection for any ordered type.
  • Equivalence classes from an arbitrary relation, with transitive closure and stable ordering.

Weaknesses

  • No linear-time selection of a single order statistic (such as the median) and no smallest- variant; use select_nth_unstable from the standard library, or reverse the order.
  • Equivalence classes are quadratic; there is no key-based fast path.

Exercises

  1. Show that the bounded heap finds the largest elements, and count its comparisons on a sorted input.
  2. Estimate the expected number of heap replacements on a random permutation (the element at position enters with probability ).
  3. Show that the transitive closure of a symmetric, reflexive relation is an equivalence relation.
  4. Give a relation for which the result depends on the transitive closure, and explain why “within 2” clusters are unbounded in size.
  5. Group words into anagram classes in by sorting with a canonical key.
Hints and answers
  1. Keep a min-heap of size holding the largest seen so far; a new element larger than the minimum replaces it. On sorted (ascending) input every new element replaces the root, costing about comparisons, so .
  2. The element at position is among the largest of the first with probability , so the expected number of replacements is .
  3. The closure adds the missing transitive pairs but keeps reflexivity and symmetry (composing a path with its reverse gives the reverse), and it is transitive by construction; hence an equivalence relation.
  4. “Within 2” () is not transitive, so the closure chains into one class that can contain arbitrarily many elements, and its size is unbounded.
  5. Sort the letters of each word to form a canonical key (so that anagrams share a key), then sort the words by key and group equal keys: comparisons of short strings.

Further reading

  • D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed., Addison-Wesley, 1998, sections 5.2.3 and 5.3.3.
  • M. Blum, R. W. Floyd, V. Pratt, R. L. Rivest and R. E. Tarjan, “Time bounds for selection”, Journal of Computer and System Sciences 7 (1973) 448–461.
  • B. A. Galler and M. J. Fischer, “An improved equivalence algorithm”, Communications of the ACM 7 (1964) 301–303.
  • W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, Numerical Recipes, 3rd ed., Cambridge University Press, 2007, section 8.5–8.6.