Algorithm Search⌘K

Modelintro

Comparison model

Also called decision tree model, comparison-based model.

A model where an algorithm learns about its input only by comparing two items. The cost is the number of comparisons.

The machine

The input is a sequence of items from a set with a total order. The algorithm cannot read the items. It can only ask "is ai<aja_i < a_j?" or, with a three-way comparison, "is aia_i less than, equal to or larger than aja_j?". It can move and copy items, and it can do any other computation that does not look at the items.

An algorithm in this model is a decision tree. Each inner node is a comparison. Each branch is an outcome. Each leaf is an output. The run on an input follows one path from the root to a leaf.

What it counts

The cost is the number of comparisons. The worst-case cost is the depth of the tree. The average cost is the average depth of the leaves, over a distribution of inputs. The other work of the algorithm is free in the model. For most algorithms it is a constant factor of the number of comparisons, so the model also gives the time.

Relation to other models

The word RAM can do arithmetic on the items and use them as addresses. So it can beat the bounds of the comparison model. Counting sort, radix sort and hash tables do this. The comparison model is still the right model for code that must work for any type with an order, such as the library sort of most languages, which takes a comparison function.

Known results in the model

  • Sorting needs ⌈lg⁡(n!)⌉=nlg⁡n−Θ(n)\lceil \lg(n!) \rceil = n \lg n - \Theta(n) comparisons in the worst case and on average. A binary tree with n!n! leaves has a depth of at least lg⁡(n!)\lg(n!). See the sorting problem.
  • Search in a sorted array needs ⌈lg⁡(n+1)⌉\lceil \lg(n+1) \rceil three-way comparisons. See search in a sorted array.
  • The maximum of nn items needs n−1n - 1 comparisons. Each item except the maximum must lose one comparison.
  • The maximum and the minimum together need ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 comparisons.
  • Merging two sorted lists of nn items each needs 2n−12n - 1 comparisons in the worst case.

References

  1. Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, fourth edition, Section 8.1
  2. Donald E. Knuth, The Art of Computer Programming, Volume 3, second edition, Section 5.3.1

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 proof
  • add a proof in proofs/ (06.5)
Lean
  • name a Lean module in the lean field (07)
Visual
  • add viz/scene.ts or a figure (10)
Writing
  • the lead paragraph