Study Atlas › Computer Science › Algorithms

Algorithms and Big-O complexity

An algorithm is a finite sequence of well-defined steps; Big-O notation describes how its cost grows with input size.

Edited by Alex C, EduAlx · Sources cited below

Explanation

Common classes: O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n), O(n²) quadratic, O(2ⁿ) exponential. Knuth popularised asymptotic analysis in computing. Worst, average and best cases can differ.

Example

Linear search is O(n); binary search on a sorted array is O(log n): 1 million items need at most about 20 comparisons.

Code

def binary_search(a, x):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == x: return mid
        if a[mid] < x: lo = mid + 1
        else: hi = mid - 1
    return -1

How it works, step by step

  1. Define the input size n
  2. Count basic operations as a function of n
  3. Keep the dominant term
  4. Drop constant factors

Open the interactive page with diagrams →

People behind it

References

  1. D. E. Knuth, SIGACT News 1976, 8(2), 18–24 (Big Omicron and Big Omega and Big Theta).

Textbooks

Related topics

Sorting algorithms (quicksort, mergesort, heapsort)String algorithms and pattern matchingGraph algorithms: BFS, DFS and Dijkstra's shortest pathGreedy algorithms and minimum spanning treesDynamic programmingError-detecting and error-correcting codesData structures: arrays, linked lists, stacks, queuesHuman–computer interaction and usabilityHash tablesTesting and debugging