[[File:GCD_through_successive_subtractions.svg|thumb|Flowchart of an algorithm to find the greatest common divisor of two numbers.|alt=In a loop, subtract the larger number against the smaller number. Halt the loop when the subtraction will make a number negative. Assess two numbers, whether one of them is equal to zero or not. If yes, take the other number as the greatest common divisor. If no, put the two numbers in the subtraction loop again.]] In mathematics and computer science, an algorithm () is a finite sequence[1] of mathematically rigorous logical instructions, typically used to solve a class of specific problems or to perform a computation.[2] Algorithms are used as specifications for performing calculations and data processing. More advanced algorithms can use conditionals to divert the code execution through various routes (referred to as automated decision-making) and deduce valid inferences (referred to as automated reasoning).
In contrast, a heuristic is an approach to solving problems without well-defined correct or optimal results.[3] For example, although social media recommender systems are commonly called "algorithms", they actually rely on heuristics as there is no truly "correct" recommendation.
As an effective method, an algorithm can be expressed within a finite amount of space and time[4] and in a well-defined formal language[5] for calculating a function.[6] Starting from an initial state and input, a computation occurs at each step, eventually producing output[7] and terminating. The transition between states can be non-deterministic; randomized algorithms incorporate random input.[8]
Around 825 AD, Persian scientist and polymath Muḥammad ibn Mūsā al-Khwārizmī wrote kitāb al-ḥisāb al-hindī ("Book of Indian computation") and kitab al-jam' wa'l-tafriq al-ḥisāb al-hindī ("Addition and subtraction in Indian arithmetic"). In the early 12th century, Latin translations of these texts involving the Hindu–Arabic numeral system and arithmetic appeared, for example Liber Alghoarismi de practica arismetrice, attributed to John of Seville, and Liber Algoritmi de numero Indorum, attributed to Adelard of Bath.[9] Here, alghoarismi or algoritmi is the Latinization of Al-Khwarizmi's name; the text starts with the phrase Dixit Algoritmi, or "Thus spoke Al-Khwarizmi".
[[File:Al-Khwarizmi portrait.jpg|thumb|Muḥammad ibn Mūsā al-Khwārizmī: The 9th-century mathematician whose name is the origin of the word 'algorithm'.]]
The word algorism in English came to mean the use of place-value notation in calculations; it occurs in the Ancrene Wisse from circa 1225.[10] By the time Geoffrey Chaucer wrote The Canterbury Tales in the late 14th century, he used a variant of the same word in describing augrym stones, stones used for place-value calculation.[11][12] In the 15th century, under the influence of the Greek word ἀριθμός (arithmos, "number"; cf. "arithmetic"), the Latin word was altered to algorithmus.[13] By 1596, this form of the word was used in English, as algorithm, by Thomas Hood.[14]
One informal definition is "a set of rules that precisely defines a sequence of operations", which would include all computer programs, and any bureaucratic procedure[15] or cook-book recipe.[16] In general, a program is an algorithm only if it stops eventually.[17] Formally, algorithm is an explicit set of instructions to produce an output, that can be followed by a computer or a human performing specific operations on symbols.[18]
Step-by-step procedures for solving mathematical problems have been recorded since antiquity. This includes in Babylonian mathematics (around 2500 BC),[19] Egyptian mathematics (around 1550 BC), Indian mathematics (around 800 BC and later),[20][21] the Ifa Oracle (around 500 BC),[22] Greek mathematics (around 240 BC),[23] Chinese mathematics (around 200 BC and later),[24] and Arabic mathematics (around 800 AD).[25]
The earliest evidence of algorithms is found in ancient Mesopotamian mathematics. A Sumerian clay tablet found in Shuruppak near Baghdad and dated to describes the earliest division algorithm. During the Hammurabi dynasty , Babylonian clay tablets described algorithms for computing formulas.[26] Algorithms were also used in Babylonian astronomy. Babylonian clay tablets describe and employ algorithmic procedures to compute the time and place of significant astronomical events.[27]
Algorithms for arithmetic are also found in ancient Egyptian mathematics, dating back to the Rhind Mathematical Papyrus . Algorithms were later used in ancient Hellenistic mathematics. Two examples are the Sieve of Eratosthenes, which was described in the Introduction to Arithmetic by Nicomachus,[28] and the Euclidean algorithm, which was first described in Euclid's Elements ().Examples of ancient Indian mathematics included the Shulba Sutras, the Kerala School, and the Brāhmasphuṭasiddhānta.
In the 9th century, Muḥammad ibn Mūsā al-Khwārizmī revolutionized the field by establishing the algorithm as a systematic, finite sequence of logical steps to solve mathematical problems. In his influential work, The Compendious Book on Calculation by Completion and Balancing, he moved beyond specific numerical solutions to introduce general procedures for algebraic reduction and balancing. This transformed mathematics into a 'mechanical' process of well-defined rules—a fundamental shift that laid the groundwork for modern algorithmic theory. The Latin translation of his arithmetic treatise, titled Algoritmi de numero Indorum, led to the term algorithm being derived from the Latinization of his name, Algoritmi, specifically to describe this new rule-based approach to mathematics.[29]
The first cryptographic algorithm for deciphering encrypted code was developed by Al-Kindi, a 9th-century Arab mathematician, in A Manuscript On Deciphering Cryptographic Messages. He gave the first description of cryptanalysis by frequency analysis, the earliest codebreaking algorithm.
Weight-driven clocks were a key European invention in Middle Ages, specifically the verge escapement mechanism[30] producing the tick of mechanical clocks. Accurate automatic machines[31] led to mechanical automata in the 13th century and computational machines—the difference and analytical engines of Charles Babbage and Ada Lovelace in the mid-19th century.[32] Lovelace designed the first algorithm intended for a computer, Babbage's analytical engine, the first real Turing-complete computer, more than the mechanical calculators of the time. Although the full implementation of Babbage's second device was only built decades after her lifetime, Lovelace has been called "history's first programmer".
The Jacquard loom, a precursor to punch cards, and telephone switching machines led to the development of the first computers.[33] By the mid-19th century, the telegraph, was in use throughout the world. By the late 19th century, ticker tape () and punch cards (c. 1890) were developed. Then came the teleprinter () with its punched-paper use of Baudot code on tape.
Telephone-switching networks of electromechanical relays were invented in 1835. These led to the invention of the digital adding device by George Stibitz in 1937. While working in Bell Laboratories, he observed the "burdensome" use of mechanical calculators with gears, prompting him to create an experimental digital adder at home.[34][35]
[[File:Diagram for the computation of Bernoulli numbers.jpg|thumb|Ada Lovelace's diagram from "Note G", the first published computer algorithm]]
In 1928, a partial formalization of the modern concept of algorithms began with attempts to solve David Hilbert's Entscheidungsproblem (decision problem). Later formalizations were framed as attempts to define "effective calculability"[36] or "effective method".[37] Those formalizations included the Gödel–Herbrand–Kleene recursive functions of 1930, 1934 and 1935, Alonzo Church's lambda calculus of 1936, Emil Post's Formulation 1 of 1936, and Alan Turing's Turing machines of 1936–37 and 1939.
The mathematical formalization of the notion of algorithm is distinct from the formalization of computable functions. In particular, the equivalence of classical models of computability does not by itself provide a formal definition of an algorithm, since different algorithms can compute the same function. Several approaches have therefore sought to characterize algorithms as mathematical objects.
Yuri Gurevich developed the theory of abstract state machines (ASMs) as a formal characterization of sequential algorithms. His sequential ASM thesis states that every sequential algorithm is behaviorally equivalent to a sequential ASM, with the equivalence established step by step. Gurevich formulated axioms for sequential algorithms and proved the corresponding characterization theorem.[38]
A different approach was developed by Yiannis N. Moschovakis, who proposed a mathematical theory of algorithms based on set-theoretic objects and distinguished algorithms from their implementations. His theory was developed in connection with questions of computational complexity and with the mathematical analysis of particular algorithms.[39]
For decades, it was assumed that algorithm evolution progresses from heuristics to formal algorithms. A Symbolic integration provides a classic illustration. In 1961, James Slagle's program SAINT used heuristics to solve 52 of 54 freshman calculus exercises from an MIT textbook (≈96%). In 1967, Larry Moses's SIN refined the heuristics and achieved 100% success, though it remained heuristic. Finally, in 1969, Robert Risch introduced the Risch Algorithm with formal guarantees. This trajectory defined the traditional path: heuristics evolving until a definitive, guaranteed algorithm emerged.
However, the rise of transformer-based AI has inverted this sequence — classical algorithms are now being displaced by heuristics once again.
Algorithms have evolved and improved in many ways as time goes on. Common uses of algorithms today include social media apps like Instagram and YouTube. Algorithms are used as a way to analyze what people like and push more of those things to the people who interact with them. Quantum computing uses quantum algorithm procedures to solve problems faster. More recently, in 2024, NIST updated their post-quantum encryption standards, which includes new encryption algorithms to enhance defenses against attacks using quantum computing.
Algorithms can be expressed in many kinds of notation, including natural languages, pseudocode, flowcharts, drakon-charts, programming languages or control tables. Natural language expressions of algorithms tend to be verbose and ambiguous and are rarely used for complex or technical algorithms. Pseudocode, flowcharts, drakon-charts, and control tables are structured expressions of algorithms that avoid common ambiguities of natural language. Programming languages are primarily for expressing algorithms in a computer-executable form but are also used to define or document algorithms.
There are many possible representations and Turing machine programs can be expressed as a sequence of machine tables (see finite-state machine, state-transition table, and control table for more), as flowcharts and drakon-charts (see state diagram for more), as a form of rudimentary machine code or assembly code called "sets of quadruples", and more. Algorithm representations can also be classified into three accepted levels of Turing machine description: high-level description, implementation description, and formal description.[40] A high-level description describes the qualities of the algorithm itself, ignoring how it is implemented on the Turing machine. An implementation description describes the general manner in which the machine moves its head and stores data to carry out the algorithm, but does not give exact states. In the most detail, a formal description gives the exact state table and list of transitions of the Turing machine.
A flowchart is a graphical aid that describes and documents an algorithm. It has four primary symbols: arrows showing program flow, rectangles (SEQUENCE, GOTO), diamonds representing decisions, and dots (OR-tie). Sub-structures can "nest" in rectangles, but only if a single exit occurs from the superstructure.
It is often important to know the time, storage, or other cost an algorithm may require. Methods have been developed to analyse algorithms to estimate these needs. For example, an algorithm that adds up the elements of a list of n numbers would have a time requirement of , using big O notation. The algorithm only needs to remember two values: the sum of all the elements so far, and its current position in the input list. If the space required to store the input numbers is not counted, it has a space requirement of , otherwise is required.
Different algorithms may complete the same task with a different set of instructions in less or more time, space, or 'effort' than others. For example, a binary search algorithm (with cost ) outperforms a sequential search (cost ) when used for table lookups on sorted lists.
The analysis, and study of algorithms is a discipline of computer science. Algorithms are often studied abstractly, without referencing a specific programming language or implementation. Like other mathematical disciplines, it focuses on the algorithm's properties, not implementation. Pseudocode is typical for analysis as it is a simple and general representation. Most algorithms are implemented on particular hardware/software platforms and their algorithmic efficiency is tested using real code. The efficiency of a particular algorithm may be insignificant for many "one-off" problems but it can be critical for algorithms designed for fast, interactive, commercial, or long-life scientific usage. Increasing the input size often exposes inefficient algorithms that are otherwise benign.
Empirical testing is useful for uncovering unexpected interactions that affect performance. Benchmarks may be used to compare before/after potential improvements to an algorithm after program optimization. Empirical tests cannot fully replace formal analysis, and are difficult to perform fairly.[41]
To illustrate the potential improvements possible even in well-established algorithms, a recent significant innovation, relating to FFT algorithms used for image processing, can decrease processing time up to 1,000 times for medical imaging.[42] In general, speed improvements depend on special properties of the problem, which are very common in practical applications.[43]
The best case of an algorithm refers to the scenario or input for which the algorithm or data structure takes the least time and resources to complete its tasks.[44] The worst case of an algorithm is the case that causes the algorithm or data structure to consume the maximum period of time and computational resources.[45]
Algorithm design may take advantage of many different approaches, such as divide-and-conquer or dynamic programming. Techniques for designing and implementing algorithms are also called algorithm design patterns.[46] Examples include the template method pattern and the decorator pattern. An important aspect of algorithm design is efficient use of resources such as memory or time; the big O notation is used to describe how resource use changes as the size of inputs increase.[47]
Any algorithm can be computed by any Turing complete model. Turing completeness only requires four instruction types—conditional GOTO, unconditional GOTO, assignment, HALT. Tausworthe augments the three Böhm-Jacopini canonical structures:[48] SEQUENCE, IF-THEN-ELSE, and WHILE-DO, with two more: DO-WHILE and CASE.[49] An additional benefit of a structured program is that it lends itself to proofs of correctness using mathematical induction.[50]
By themselves, algorithms are not usually patentable. In the United States, a claim consisting solely of simple manipulations of abstract concepts, numbers, or signals does not constitute "processes", so algorithms are not patentable (as in Gottschalk v. Benson). However, practical applications of algorithms can be patentable. For example, in Diamond v. Diehr, the application of a simple feedback algorithm to aid in the curing of synthetic rubber was deemed patentable. The patenting of software is controversial,[51] and there are criticized patents involving algorithms, especially data compression algorithms, such as Unisys's LZW patent. Additionally, some cryptographic algorithms have export restrictions (see export of cryptography).
Another way of classifying algorithms is by their design methodology or paradigm. Some common paradigms are:
For optimization problems there is a more specific classification of algorithms; an algorithm for such problems may fall into one or more of the general categories described above as well as into one of the following:
One of the simplest algorithms finds the largest number in a list of numbers of random order. Finding the solution requires looking at every number in the list. From this follows a simple algorithm, which can be described in plain English as:
High-level description:
(Quasi-)formal description: Written in prose but much closer to the high-level language of a computer program, the following is the more formal coding of the algorithm in pseudocode or pidgin code:
Input: A list of numbers ''L''. Output: The largest number in the list ''L''.
'''if''' ''L.size'' = 0 '''return''' null
''largest'' ← ''L''[0]
'''for each''' ''item'' '''in''' ''L'', '''do'''
'''if''' ''item'' > ''largest'', '''then'''
''largest'' ← ''item''
'''return''' ''largest''Artificial intelligence systems have been used to discover and optimize algorithms. In 2023, Google DeepMind introduced AlphaDev, a reinforcement learning system based on AlphaZero that discovered improved sorting and hashing algorithms.[56] In a paper published in Nature, AlphaDev was reported to have discovered small sorting algorithms that outperformed previously known human benchmarks and were integrated into the LLVM standard C++ sorting library.[57]
In 2025, Google DeepMind introduced AlphaEvolve, an evolutionary coding agent powered by large language models for general-purpose algorithm discovery and optimization.[58] AlphaEvolve uses language models to propose code changes, automated evaluators to test candidate solutions, and an evolutionary process to improve promising algorithms over multiple iterations.[59]