Programming Search⌘K

Conceptcore

Algorithm

Also called algorithm, algorithms, procedure, method of computation, effective procedure, computational method, step-by-step procedure.

An algorithm is a finite list of exact steps that takes an input and gives the answer to every instance of a problem. A program is one way to write an algorithm down for a machine.

Applies to
core-languages

Idea

An algorithm is a method to solve a problem, written as steps so exact that a machine or a careful person can follow them with no judgment. It takes an input, does a finite number of steps and gives an output, and it must work for every input of the problem, not only for the examples that the author tried. A program is an algorithm written in a programming language, together with the details that the language and the machine need. One problem usually has many algorithms, and they can differ greatly in the number of steps they take.

def linear_search(xs, target):  # look at each item in turn
    steps = 0
    for i, x in enumerate(xs):
        steps += 1
        if x == target:
            return i, steps
    return -1, steps


def binary_search(xs, target):  # xs must be sorted
    lo, hi, steps = 0, len(xs), 0
    while lo < hi:  # the target, if present, is in xs[lo:hi]
        steps += 1
        mid = (lo + hi) // 2
        if xs[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    found = lo < len(xs) and xs[lo] == target
    return (lo if found else -1), steps


xs = list(range(0, 2_000_000, 2))  # one million even numbers, sorted
for t in (10, 1_999_998, 7):
    print(f"target {t:>9}: linear {linear_search(xs, t)}, binary {binary_search(xs, t)}")

print("unsorted input:", binary_search([3, 1, 2], 3))


def collatz_steps(n):  # exact steps, but nobody has proved that it stops for every n
    steps = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        steps += 1
    return steps


print("collatz steps for 27:", collatz_steps(27))
Output
target        10: linear (5, 6), binary (5, 20)
target   1999998: linear (999999, 1000000), binary (999999, 20)
target         7: linear (-1, 1000000), binary (-1, 20)
unsorted input: (-1, 2)
collatz steps for 27: 111

The program solves one problem, find a number in a sorted list, with two algorithms. Linear search looks at each item in turn, so in the worst case it looks at all one million items. Binary search compares the target with the middle item and discards half of the list at each step, so it never needs more than 20 steps, because 2 to the power 20 is more than one million. Binary search is faster only because it uses a fact about the input: the list is sorted. With an unsorted list, it gives a wrong answer and no error. The last function follows exact steps, but nobody has proved that it stops for every starting number, so it is not known to be an algorithm.

How it works

What makes a procedure an algorithm. The NIST dictionary defines an algorithm as "A computable set of steps to achieve a desired result."1 Donald Knuth gave five properties in The Art of Computer Programming. Finiteness: it stops after a finite number of steps for every input. Definiteness: each step is exact and has one meaning. Input: it takes zero or more values. Output: it gives one or more values that relate to the input. Effectiveness: each step is basic enough that a person with pencil and paper could do it in a finite time. A procedure that can run forever, such as a server loop or the Collatz function above, is a computation but not an algorithm in this strict sense.

Problem, algorithm and program. A problem states what the answer must be for each input, for example "the index of the target in a sorted list, or a sign that it is not there". An algorithm states how to get the answer. A program states the algorithm in one language, and adds choices that the algorithm leaves open: the types of the values, what happens at the limits of the machine, how errors are reported and what the function returns when the target is absent. The algorithm is the same in each language of this page; the contracts of the library functions differ.

Preconditions and correctness. An algorithm is correct when it gives the right output for every input that meets its precondition. Binary search has the precondition that the input is sorted. The library functions state it in their documentation: Java's Arrays.binarySearch says "The array must be sorted (as by the sort(long[]) method) prior to making this call. If it is not sorted, the results are undefined."3 Rust says that "If the slice is not sorted, the returned result is unspecified and meaningless."5 The usual way to show that a loop is correct is an invariant, a statement that is true before and after each pass. For binary search it is "if the target is in the list, it is between lo and hi". Each pass makes the range smaller, so the loop stops, and when it stops the invariant gives the answer.

Cost. Two algorithms for one problem are compared by how the number of steps grows with the size of the input, written in big-O notation. Linear search takes O(n) steps and binary search O(log n) steps. For small inputs the difference is small, and a simple algorithm with a small constant can be faster. For large inputs the growth rate decides. The analysis of algorithms is a field of its own, and the algorithm site covers it.

Algorithms in the standard library. Programs seldom write the classic algorithms again. Each language ships sorting and searching, and the documentation gives the contract. Python's bisect module keeps "a list in sorted order without having to sort the list after each insertion".2 Go's slices.BinarySearch "returns the earliest position where target is found, or the position where target would appear in the sort order; it also returns a bool saying whether the target is really found in the slice."4 C's bsearch takes a comparison function and needs an array in which "all the elements that compare less than must appear before all the elements that compare equal to, and those must appear before all the elements that compare greater than the key object."6 C++'s std::lower_bound "Searches for the first element in the partitioned source range [first, last) which is not ordered before value".10 .NET returns "the bitwise complement of the index of the first element that is larger than value" when the value is absent.7 JavaScript has no binary search, and its sort has a surprise: "The default sort order is ascending, built upon converting the elements into strings".8

Algorithms and data structures. An algorithm works on data in some layout, and the layout decides which algorithms are possible. Binary search needs random access to the middle item, so it works on an array but not on a linked list. A hash table finds a key in constant time on average and has no order, so it cannot answer "the first key greater than 50". Niklaus Wirth gave a book the title Algorithms + Data Structures = Programs in 1976 for this reason.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CStandard library
C#Standard library
JavaScriptStandard library
TypeScriptStandard libraryTypeScript uses the sort of JavaScript, with the same string order by default, but no example file exists.
GoStandard library
RustStandard library
KotlinStandard libraryThe Kotlin standard library has sorted, sortedBy, sortWith and binarySearch on lists, but no example file exists because kotlinc is not installed.
SQLNativeORDER BY states the order of the result, and the query planner chooses the sort, the join and the index, so the program states the problem and not the algorithm.
BashIdiomThe sort command sorts lines, with -n for numbers, and other algorithms are loops over arrays, but no example file exists.
PowerShellStandard librarySort-Object sorts objects by properties, and the .NET methods such as Array.BinarySearch are available, but no example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and describes no computation.
CSSDoes not applyCSS states rules, and the browser runs the layout algorithm.
Regular expressionsDoes not applyA pattern describes text to match, and the engine runs the matching algorithm.
Language Verdict Mechanism
Python stdlib list.sort, sorted, the bisect module
JavaScript stdlib Array.prototype.sort; no binary search
TypeScript stdlib as JavaScript
Java stdlib Arrays.sort, Arrays.binarySearch, Collections
Kotlin stdlib sorted, sortedBy, binarySearch on lists
C# stdlib Array.Sort, Array.BinarySearch, LINQ OrderBy
Go stdlib slices.Sort, slices.BinarySearch, sort.Search
Rust stdlib sort, sort_unstable, binary_search, partition_point
C stdlib qsort and bsearch with a comparison function
C++ stdlib <algorithm>: std::ranges::sort, lower_bound
Bash idiom the sort command; loops for the rest
PowerShell stdlib Sort-Object; .NET methods
SQL native ORDER BY; the engine chooses the algorithm
Regex n/a the engine runs a matching algorithm
HTML n/a markup, not computation
CSS n/a the layout algorithm belongs to the browser

Every general-purpose language ships the common algorithms, and the differences are in the contracts. A search that finds nothing returns the insertion point with no flag in Python's bisect, a negative number in Java and C#, a pair in Go, a Result in Rust, a null pointer in C and an iterator in C++. Sorts differ in stability: Python's sort, Java's object sort, Rust's sort and C#'s LINQ OrderBy keep equal items in their order, while C#'s Array.Sort, Go's slices.Sort, Rust's sort_unstable and C++'s std::sort do not. SQL is the clearest case of an algorithm that the programmer does not write: a query states the result, and the planner chooses the sort, the join and the index to use.

The example files show the same contracts. Python shows bisect_left, insort and the key argument, and a wrong block searches an unsorted list. JavaScript shows the string order of the default sort. Java prints the overflow that Joshua Bloch found in the textbook binary search. Go shows sort.Search on a predicate, Rust shows partition_point, C shows a comparison function that cannot overflow, and C++ shows lower_bound and a sort by a projection.

PythonGitHub
import bisect

scores = [12, 31, 47, 47, 58, 90]
print("bisect_left 47:", bisect.bisect_left(scores, 47))
print("bisect_right 47:", bisect.bisect_right(scores, 47))
print("bisect_left 50:", bisect.bisect_left(scores, 50), "(where 50 would go)")

bisect.insort(scores, 50)  # finds the place in O(log n) steps, then shifts the tail
print("after insort:", scores)

people = [("Ada", 1815), ("Alan", 1912), ("Grace", 1906)]
people.sort(key=lambda p: p[1])  # stable: equal keys keep their order
i = bisect.bisect_left(people, 1900, key=lambda p: p[1])
print("born from 1900:", [p[0] for p in people[i:]])
Output
bisect_left 47: 2
bisect_right 47: 4
bisect_left 50: 4 (where 50 would go)
after insort: [12, 31, 47, 47, 50, 58, 90]
born from 1900: ['Grace', 'Alan']

This code runs but gives a wrong answer on purpose.

import bisect

scores = [90, 12, 58, 31, 47]  # not sorted
i = bisect.bisect_left(scores, 90)
print("index:", i, "found:", i < len(scores) and scores[i] == 90)
print("90 in scores:", 90 in scores)
Output
index: 5 found: False
90 in scores: True
  • Verdict: stdlib. list.sort and sorted are stable, and the bisect module does binary search on a sorted list. bisect_left gives the first place where the value could go and bisect_right the place after equal items, so the two together give the range of equal items. Since Python 3.10 the functions take a key argument. insort finds the place in O(log n) steps, but the insertion shifts the tail of the list, so it is still O(n).
  • The wrong block searches a list that is not sorted. bisect_left returns 5 and the program says that 90 is absent, although 90 in scores is true. Nothing checks the precondition.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<int> xs{90, 12, 58, 31, 47};
    std::ranges::sort(xs); // O(n log n) comparisons, not stable
    for (int t : {58, 50}) {
        auto it = std::ranges::lower_bound(xs, t);
        bool found = it != xs.end() && *it == t;
        std::cout << "search " << t << ": index " << (it - xs.begin())
                  << ", found " << std::boolalpha << found << '\n';
    }
    std::cout << "binary_search 50: " << std::ranges::binary_search(xs, 50) << '\n';

    struct Person { std::string name; int born; };
    std::vector<Person> ps{{"Grace", 1906}, {"Ada", 1815}, {"Alan", 1912}};
    std::ranges::stable_sort(ps, {}, &Person::born); // sort by a projection
    for (const auto& p : ps) std::cout << p.name << ' ' << p.born << '\n';
}
Output
search 58: index 3, found true
search 50: index 3, found false
binary_search 50: false
Ada 1815
Grace 1906
Alan 1912
  • Verdict: stdlib. <algorithm> has dozens of algorithms over ranges of iterators, and C++20 added versions in std::ranges that take a whole container and a projection. std::ranges::sort takes O(n log n) comparisons and is not stable; stable_sort is. lower_bound returns an iterator to the first item that is not less than the value, and binary_search returns only a bool. The projection &Person::born sorts by one field with no comparison function.
JavaGitHub
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int[] xs = {12, 31, 47, 58, 90};
        System.out.println("search 58: " + Arrays.binarySearch(xs, 58));
        int r = Arrays.binarySearch(xs, 50);
        System.out.println("search 50: " + r + ", insertion point " + (-r - 1));

        List<String> names = new java.util.ArrayList<>(List.of("Grace", "Ada", "Alan"));
        Collections.sort(names); // stable for objects
        System.out.println(names + " Alan at " + Collections.binarySearch(names, "Alan"));

        int lo = 1_500_000_000, hi = 2_000_000_000; // indexes of a very large array
        System.out.println("(lo + hi) / 2   = " + (lo + hi) / 2);
        System.out.println("(lo + hi) >>> 1 = " + ((lo + hi) >>> 1));
        System.out.println("lo + (hi - lo) / 2 = " + (lo + (hi - lo) / 2));
    }
}
Output
search 58: 3
search 50: -4, insertion point 3
[Ada, Alan, Grace] Alan at 1
(lo + hi) / 2   = -397483648
(lo + hi) >>> 1 = 1750000000
lo + (hi - lo) / 2 = 1750000000
  • Verdict: stdlib. Arrays.sort sorts arrays of primitives with a dual-pivot quicksort and arrays of objects with a stable merge sort. Arrays.binarySearch returns the index, or -(insertion point) - 1 when the key is absent, so a negative result also says where to insert. The last lines show the bug that Joshua Bloch reported in 2006: with large indexes, lo + hi overflows int and the midpoint is negative. The unsigned shift and lo + (hi - lo) / 2 give the right midpoint.
#include <stdio.h>
#include <stdlib.h>

static int cmp_int(const void *pa, const void *pb) {
    int a = *(const int *)pa, b = *(const int *)pb;
    return (a > b) - (a < b); /* not a - b, which can overflow */
}

int main(void) {
    int xs[] = {90, 12, 58, 31, 47};
    size_t n = sizeof xs / sizeof xs[0];
    qsort(xs, n, sizeof xs[0], cmp_int);
    for (size_t i = 0; i < n; i++)
        printf(i ? " %d" : "%d", xs[i]);
    printf("\n");

    int keys[] = {58, 50};
    for (int k = 0; k < 2; k++) {
        int *p = bsearch(&keys[k], xs, n, sizeof xs[0], cmp_int);
        if (p)
            printf("search %d: found at %td\n", keys[k], p - xs);
        else
            printf("search %d: not found\n", keys[k]);
    }
    return 0;
}
Output
12 31 47 58 90
search 58: found at 3
search 50: not found
  • Verdict: stdlib. qsort and bsearch from <stdlib.h> work on any array through void pointers, the size of an item and a comparison function. The comparison returns a negative, zero or positive int. The common shortcut return a - b; overflows when the values are far apart, which is undefined behavior for int, so the file uses (a > b) - (a < b). bsearch returns a null pointer when the key is absent and does not give the insertion point. The C standard does not say which algorithm qsort uses, and it is not stable.
int[] xs = [12, 31, 47, 58, 90];
Console.WriteLine($"search 58: {Array.BinarySearch(xs, 58)}");
int r = Array.BinarySearch(xs, 50);
Console.WriteLine($"search 50: {r}, insert at {~r}");

var names = new List<string> { "Grace", "Ada", "Alan" };
names.Sort(StringComparer.Ordinal); // not stable
Console.WriteLine($"{string.Join(", ", names)}; Alan at {names.BinarySearch("Alan", StringComparer.Ordinal)}");

var people = new[] { ("Grace", 1906), ("Ada", 1815), ("Alan", 1912), ("Edsger", 1930) };
var byYear = people.OrderBy(p => p.Item2).Select(p => p.Item1); // LINQ OrderBy is stable
Console.WriteLine(string.Join(" < ", byYear));
Output
search 58: 3
search 50: -4, insert at 3
Ada, Alan, Grace; Alan at 1
Ada < Grace < Alan < Edsger
  • Verdict: stdlib. Array.Sort and List<T>.Sort use an introspective sort, which is not stable. LINQ's OrderBy is stable. Array.BinarySearch returns the index, or the bitwise complement of the insertion point, so ~r gives the place to insert. The comparer must be the same for the sort and the search: here both use ordinal string order.
JavaScriptGitHub
const nums = [10, 9, 1, 100, 25];
console.log("default sort:", [...nums].sort());
console.log("numeric sort:", [...nums].sort((a, b) => a - b));

// JavaScript has no binary search in the standard library.
function lowerBound(xs, target) {
  let lo = 0;
  let hi = xs.length;
  while (lo < hi) {
    const mid = (lo + hi) >>> 1;
    if (xs[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

const sorted = [...nums].sort((a, b) => a - b);
for (const t of [25, 26]) {
  const i = lowerBound(sorted, t);
  console.log(t, "index", i, "found", sorted[i] === t);
}
Output
default sort: [ 1, 10, 100, 25, 9 ]
numeric sort: [ 1, 9, 10, 25, 100 ]
25 index 3 found true
26 index 4 found false
  • Verdict: stdlib. Array.prototype.sort sorts in place and is stable since ECMAScript 2019. With no comparison function it converts the items to strings, so 100 comes before 25 and 9. The fix is a comparison function such as (a, b) => a - b, or toSorted for a sorted copy. The standard library has no binary search, so the file writes a lower bound with a half-open range; >>> 1 halves the sum as an unsigned 32-bit value, which works for any array index.
package main

import (
	"cmp"
	"fmt"
	"slices"
	"sort"
)

func main() {
	xs := []int{90, 12, 58, 31, 47}
	slices.Sort(xs) // not stable
	fmt.Println("sorted:", xs)

	for _, t := range []int{58, 50} {
		i, found := slices.BinarySearch(xs, t)
		fmt.Printf("search %d: index %d, found %v\n", t, i, found)
	}

	// sort.Search finds the first index where a monotone predicate is true.
	n := sort.Search(1000, func(k int) bool { return k*k >= 500 })
	fmt.Println("smallest k with k*k >= 500:", n)

	type person struct {
		name string
		born int
	}
	ps := []person{{"Grace", 1906}, {"Ada", 1815}, {"Alan", 1912}}
	slices.SortStableFunc(ps, func(a, b person) int { return cmp.Compare(a.born, b.born) })
	fmt.Println(ps)
}
Output
sorted: [12 31 47 58 90]
search 58: index 3, found true
search 50: index 3, found false
smallest k with k*k >= 500: 23
[{Ada 1815} {Grace 1906} {Alan 1912}]
  • Verdict: stdlib. The slices package, from Go 1.21, has generic Sort, SortStableFunc and BinarySearch. BinarySearch returns two values, the position and whether the target is there, so the caller cannot mistake an insertion point for a match. sort.Search is more general: it finds the first index where a predicate becomes true, so it also searches a range of numbers that is not stored anywhere, here the smallest k with k squared at least 500.
RustGitHub
fn main() {
    let mut xs = vec![90, 12, 58, 31, 47];
    xs.sort_unstable(); // faster, and equal items may change order
    println!("sorted: {:?}", xs);

    for t in [58, 50] {
        match xs.binary_search(&t) {
            Ok(i) => println!("search {t}: found at {i}"),
            Err(i) => println!("search {t}: not found, insert at {i}"),
        }
    }

    // partition_point: the first index where the predicate turns false
    let i = xs.partition_point(|&x| x < 40);
    println!("first item >= 40 is at {i}: {}", xs[i]);

    let mut people = vec![("Grace", 1906), ("Ada", 1815), ("Alan", 1912)];
    people.sort_by_key(|p| p.1); // stable
    println!("{:?}", people);
}
Output
sorted: [12, 31, 47, 58, 90]
search 58: found at 3
search 50: not found, insert at 3
first item >= 40 is at 2: 47
[("Ada", 1815), ("Grace", 1906), ("Alan", 1912)]
  • Verdict: stdlib. Slices have a stable sort, a faster sort_unstable and sort_by_key. binary_search returns Ok(index) when the value is there and Err(index) with the insertion point when it is not, so the type makes the caller handle both cases. partition_point gives the first index where a predicate turns false, which is a lower bound for any condition.
  • Kinds of algorithm. Deterministic algorithms give the same steps for the same input. Randomized algorithms use random choices, such as quicksort with a random pivot. Approximation algorithms give an answer close to the best one when the best is too costly to find. Online algorithms handle the input one item at a time.
  • Heuristics. A heuristic is a rule that usually gives a good answer quickly but has no proof that it is correct or best.
  • Computational method. Knuth's name for a procedure that has all the properties of an algorithm except finiteness, such as an operating system or a server.
  • Algorithm design techniques. Divide and conquer, recursion, dynamic programming, greedy choice and backtracking are general ways to find an algorithm.
  • State machines. A finite-state machine is a restricted algorithm with a fixed amount of memory.
  • Declarative programs. In SQL and in logic programming, the program states the problem and the system chooses the algorithm.

Pitfalls

  • Forgetting the precondition. Binary search on unsorted data, or with a comparison that does not match the sort order, gives wrong answers and no error.
  • Off-by-one errors. Algorithms on ranges must choose closed or half-open ranges and keep the choice. The half-open form [lo, hi) of this page makes the empty range lo == hi.
  • Overflow inside the algorithm. (lo + hi) / 2 overflows when the indexes are large, a bug that stayed in the JDK for about nine years. Bloch writes that it "fails if the sum of low and high is greater than the maximum positive int value".9 Use lo + (hi - lo) / 2. A C comparison function that returns a - b overflows in the same way.
  • The default sort order. JavaScript sorts numbers as strings by default, so [10, 9, 1].sort() gives [1, 10, 9].
  • Unstable sorts. Sorting records by a second key after the first one keeps the first order only when the sort is stable.
  • Proof by examples. An algorithm that passes the tests can fail on the empty input, one item, all equal items or the largest input. Test the edges, or test properties over random inputs.
  • Cost that grows hidden. A loop that calls a linear search, or list.insert at the front, inside another loop is quadratic. The program is fast on test data and slow on real data.

Cost

The cost of an algorithm is the number of basic steps and the memory it uses, as a function of the size of the input. The worst case gives a guarantee, the average case describes typical inputs, and the amortized cost averages over a sequence of operations. Big-O notation hides constants, so cache behavior, the cost of a comparison and the size of the input decide which of two algorithms is faster in practice. Binary search takes about log2(n) comparisons: 20 for a million items and 30 for a billion. A comparison sort needs about n log2(n) comparisons in the worst case, and no comparison sort can do better.

History

Euclid described his method for the greatest common divisor in the Elements in about 300 BC, and it is still in use. The word algorithm comes from the Latin form of the name of Muhammad ibn Musa al-Khwarizmi, a scholar in Baghdad in the ninth century whose book on calculation with Hindu-Arabic numerals reached Europe in translation. For centuries "algorism" meant arithmetic with these numerals.

The question of what a mechanical procedure is became exact in 1936. Alonzo Church defined it with the lambda calculus, Alan Turing defined it with his machines, and Turing showed in 1937 that the two definitions are equivalent. Turing also showed that no algorithm can decide for every program whether it stops. Donald Knuth's The Art of Computer Programming, from 1968, made the analysis of algorithms a field and gave the five properties above.

Binary search shows how hard exact algorithms are. Jon Bentley found that most professional programmers could not write it correctly, and wrote about it in Programming Pearls in 1986. In 2006 Joshua Bloch reported that the version in the JDK, and many others, overflowed on arrays of more than about a billion items, a bug that was in the version he wrote for the JDK about nine years before.9

References

  1. algorithm, Dictionary of Algorithms and Data Structures, NIST, Definition
  2. bisect, Array bisection algorithm, Python documentation, Introduction
  3. Class Arrays, Java SE 25 API documentation, binarySearch(long[] a, long key)
  4. Package slices, Go standard library documentation, func BinarySearch
  5. Primitive type slice, Rust standard library documentation, method binary_search
  6. bsearch, bsearch_s, cppreference.com, Description
  7. Array.BinarySearch Method, .NET API documentation, Returns and remarks
  8. Array.prototype.sort(), MDN Web Docs, Description
  9. Joshua Bloch, Extra, Extra, Read All About It, Nearly All Binary Searches and Mergesorts are Broken, Google Research blog, 2006, Main text
  10. std::lower_bound, cppreference.com, Description

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/78SNNV/text.yaml