In mathematics, computer science, and related subjects, an algorithm is an effective method for solving a problem using a finite sequence of instructions. Algorithms are used for calculation, data processing, and many other fields.
Each algorithm is a list of welldefined instructions for completing a task. Starting from an initial state, the instructions describe a computation that proceeds through a welldefined series of successive states, eventually terminating in a final ending state. The transition from one state to the next is not necessarily deterministic; some algorithms, known as randomized algorithms, incorporate randomness.
A partial formalization of the concept began with attempts to solve the Entscheidungsproblem (the "decision problem") posed by David Hilbert in 1928. Subsequent formalizations were framed as attempts to define "effective calculability"^{[1]} or "effective method"^{[2]}; those formalizations included the GödelHerbrandKleene 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–7 and 1939.
AlKhwārizmī, muslim Persian astronomer and mathematician, wrote a treatise in the arabic language in 825 AD, On Calculation with Hindu–Arabic numeral system. (See algorism). It was translated from arabic into Latin in the 12th century as Algoritmi de numero Indorum (alDaffa 1977), whose title is supposedly likely intended to mean "Algoritmi on the numbers of the Indians", where "Algoritmi" was the translator's rendition of the author's name; but people misunderstanding the title treated Algoritmi as a Latin plural and this led to the word "algorithm" (Latin algorismus) coming to mean "calculation method". The intrusive "th" is most likely due to a false cognate with the Greek ἀριθμός (arithmos) meaning "numbers".
While there is no generally accepted formal definition of "algorithm," an informal definition could be "a process that performs some sequence of operations." For some people, a program is only an algorithm if it stops eventually. For others, a program is only an algorithm if it stops before a given number of calculation steps.
A prototypical example of an algorithm is Euclid's algorithm to determine the maximum common divisor of two integers.
We can derive clues to the issues involved and an informal meaning of the word from the following quotation from Boolos & Jeffrey (1974, 1999) (boldface added):
No human being can write fast enough, or long enough, or small enough† ( †"smaller and smaller without limit ...you'd be trying to write on molecules, on atoms, on electrons") to list all members of an enumerably infinite set by writing out their names, one after another, in some notation. But humans can do something equally useful, in the case of certain enumerably infinite sets: They can give explicit instructions for determining the nth member of the set, for arbitrary finite n. Such instructions are to be given quite explicitly, in a form in which they could be followed by a computing machine, or by a human who is capable of carrying out only very elementary operations on symbols^{[3]}
The term "enumerably infinite" means "countable using integers perhaps extending to infinity." Thus Boolos and Jeffrey are saying that an algorithm implies instructions for a process that "creates" output integers from an arbitrary "input" integer or integers that, in theory, can be chosen from 0 to infinity. Thus we might expect an algorithm to be an algebraic equation such as y = m + n — two arbitrary "input variables" m and n that produce an output y. As we see in Algorithm characterizations — the word algorithm implies much more than this, something on the order of (for our addition example):
The concept of algorithm is also used to define the notion of decidability. That notion is central for explaining how formal systems come into being starting from a small set of axioms and rules. In logic, the time that an algorithm requires to complete cannot be measured, as it is not apparently related with our customary physical dimension. From such uncertainties, that characterize ongoing work, stems the unavailability of a definition of algorithm that suits both concrete (in some sense) and abstract usage of the term.
Algorithms are essential to the way computers process information. Many computer programs contain algorithms that specify the specific instructions a computer should perform (in a specific order) to carry out a specified task, such as calculating employees’ paychecks or printing students’ report cards. Thus, an algorithm can be considered to be any sequence of operations that can be simulated by a Turingcomplete system. Authors who assert this thesis include Minsky (1967), Savage (1987) and Gurevich (2000):
Minsky: "But we will also maintain, with Turing . . . that any procedure which could "naturally" be called effective, can in fact be realized by a (simple) machine. Although this may seem extreme, the arguments . . . in its favor are hard to refute"^{[4]}.
Gurevich: "...Turing's informal argument in favor of his thesis justifies a stronger thesis: every algorithm can be simulated by a Turing machine ... according to Savage [1987], an algorithm is a computational process defined by a Turing machine"^{[5]}.
Typically, when an algorithm is associated with processing information, data is read from an input source, written to an output device, and/or stored for further processing. Stored data is regarded as part of the internal state of the entity performing the algorithm. In practice, the state is stored in one or more data structures.
For any such computational process, the algorithm must be rigorously defined: specified in the way it applies in all possible circumstances that could arise. That is, any conditional steps must be systematically dealt with, casebycase; the criteria for each case must be clear (and computable).
Because an algorithm is a precise list of precise steps, the order of computation will always be critical to the functioning of the algorithm. Instructions are usually assumed to be listed explicitly, and are described as starting "from the top" and going "down to the bottom", an idea that is described more formally by flow of control.
So far, this discussion of the formalization of an algorithm has assumed the premises of imperative programming. This is the most common conception, and it attempts to describe a task in discrete, "mechanical" means. Unique to this conception of formalized algorithms is the assignment operation, setting the value of a variable. It derives from the intuition of "memory" as a scratchpad. There is an example below of such an assignment.
For some alternate conceptions of what constitutes an algorithm see functional programming and logic programming .
Some writers restrict the definition of algorithm to procedures that eventually finish. In such a category Kleene places the "decision procedure or decision method or algorithm for the question".^{[6]} Others, including Kleene, include procedures that could run forever without stopping; such a procedure has been called a "computational method"^{[7]} or "calculation procedure or algorithm (and hence a calculation problem) in relation to a general question which requires for an answer, not yes or no, but the exhibiting of some object".^{[8]}
Minsky makes the pertinent observation, in regards to determining whether an algorithm will eventually terminate (from a particular starting state):
But if the length of the process isn't known in advance, then "trying" it may not be decisive, because if the process does go on forever — then at no time will we ever be sure of the answer.^{[4]}
As it happens, no other method can do any better, as was shown by Alan Turing with his celebrated result on the undecidability of the socalled halting problem. There is no algorithmic procedure for determining of arbitrary algorithms whether or not they terminate from given starting states. The analysis of algorithms for their likelihood of termination is called termination analysis.
See the examples of (im)"proper" subtraction at partial function for more about what can happen when an algorithm fails for certain of its input numbers — e.g., (i) nontermination, (ii) production of "junk" (output in the wrong format to be considered a number) or no number(s) at all (halt ends the computation with no output), (iii) wrong number(s), or (iv) a combination of these. Kleene proposed that the production of "junk" or failure to produce a number is solved by having the algorithm detect these instances and produce e.g., an error message (he suggested "0"), or preferably, force the algorithm into an endless loop.^{[9]} Davis (1958) does this to his subtraction algorithm — he fixes his algorithm in a second example so that it is proper subtraction and it terminates.^{[10]} Along with the logical outcomes "true" and "false" Kleene (1952) also proposes the use of a third logical symbol "u" — undecided^{[11]} — thus an algorithm will always produce something when confronted with a "proposition". The problem of wrong answers must be solved with an independent "proof" of the algorithm e.g., using induction:
We normally require auxiliary evidence for this [that the algorithm correctly defines a mu recursive function], e.g., in the form of an inductive proof that, for each argument value, the computation terminates with a unique value.^{[12]}
Algorithms can be expressed in many kinds of notation, including natural languages, pseudocode, flowcharts, programming languages or control tables (processed by interpreters). Natural language expressions of algorithms tend to be verbose and ambiguous, and are rarely used for complex or technical algorithms. Pseudocode, flowcharts and control tables are structured ways to express algorithms that avoid many of the ambiguities common in natural language statements, while remaining independent of a particular implementation language. Programming languages are primarily intended for expressing algorithms in a form that can be executed by a computer, but are often used as a way to define or document algorithms.
There is a wide variety of representations possible and one can express a given Turing machine program as a sequence of machine tables (see more at finite state machine and state transition table), as flowcharts (see more at state diagram), or as a form of rudimentary machine code or assembly code called "sets of quadruples" (see more at Turing machine).
Sometimes it is helpful in the description of an algorithm to supplement small "flow charts" (state diagrams) with naturallanguage and/or arithmetic expressions written inside "block diagrams" to summarize what the "flow charts" are accomplishing.
Representations of algorithms are generally classed into three accepted levels of Turing machine description:^{[13]}
In computer systems, an algorithm is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s), in order for the software on the target machines to do something. For instance, if a person is writing software that is supposed to print out a PDF document located at the operating system folder "/My Documents" at computer drive "D:" every Friday at 10PM, they will write an algorithm that specifies the following actions: "If today's date (computer time) is 'Friday,' open the document at 'D:/My Documents' and call the 'print' function". While this simple algorithm does not look into whether the printer has enough paper or whether the document has been moved into a different location, one can make this algorithm more robust and anticipate these problems by rewriting it as a formal CASE statement^{[14]} or as a (carefully crafted) sequence of IFTHENELSE statements^{[15]}. For example the CASE statement might appear as follows (there are other possibilities):
Note that CASE 3 includes two possibilities: (i) the document is NOT located at 'D:/My Documents' AND there's paper in the printer OR (ii) the document is NOT located at 'D:/My Documents' AND there's NO paper in the printer.
The sequence of IFTHENELSE tests might look like this:
These examples' logic grants precedence to the instance of "NO document at 'D:/My Documents' ". Also observe that in a wellcrafted CASE statement or sequence of IFTHENELSE statements the number of distinct actions—4 in these examples: do nothing, print the document, display 'document not found', display 'out of paper'  equals the number of cases.
Given unlimited memory, a computational machine with the ability to execute either a set of CASE statements or a sequence of IFTHENELSE statements is Turing complete. Therefore, anything that is computable can be computed by this machine. This form of algorithm is fundamental to computer programming in all its forms (see more at McCarthy formalism).
Most algorithms are intended to be implemented as computer programs. However, algorithms are also implemented by other means, such as in a biological neural network (for example, the human brain implementing arithmetic or an insect looking for food), in an electrical circuit, or in a mechanical device.
One of the simplest algorithms is to find the largest number in an (unsorted) list of numbers. The solution necessarily requires looking at every number in the list, but only once at each. From this follows a simple algorithm, which can be stated in a highlevel description English prose, as:
Highlevel description:
(Quasi)formal description: Written in prose but much closer to the highlevel language of a computer program, the following is the more formal coding of the algorithm in pseudocode or pidgin code:
Algorithm LargestNumber Input: A nonempty list of numbers L. Output: The largest number in the list L. largest ← L_{0} for each item in the list L_{≥1}, do if the item > largest, then largest ← the item return largest
For a more complex example of an algorithm, see Euclid's algorithm for the greatest common divisor, one of the earliest algorithms known.
It is frequently important to know how much of a particular resource (such as time or storage) is theoretically required for a given algorithm. Methods have been developed for the analysis of algorithms to obtain such quantitative answers (estimates); for example, the algorithm above has a time requirement of O(n), using the big O notation with n as the length of the list. At all times the algorithm only needs to remember two values: the largest number found so far, and its current position in the input list. Therefore it is said to have a space requirement of O(1), if the space required to store the input numbers is not counted, or O(n) if it is counted.
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 will usually outperform a brute force sequential search when used for table lookups on sorted lists.
The analysis and study of algorithms is a discipline of computer science, and is often practiced abstractly without the use of a specific programming language or implementation. In this sense, algorithm analysis resembles other mathematical disciplines in that it focuses on the underlying properties of the algorithm and not on the specifics of any particular implementation. Usually pseudocode is used for analysis as it is the simplest and most general representation. However, ultimately, most algorithms are usually implemented on particular hardware / software platforms and their algorithmic efficiency is eventually put to the test using real code.
Empirical testing is useful because it may uncover unexpected interactions that affect performance. For instance an algorithm that has no locality of reference may have much poorer performance than predicted because it 'thrashes the cache'. Benchmarks may be used to compare before/after potential improvements to an algorithm after program optimization.
There are various ways to classify algorithms, each with its own merits.
One way to classify algorithms is by implementation means.
Another way of classifying algorithms is by their design methodology or paradigm. There is a certain number of paradigms, each different from the other. Furthermore, each of these categories will include many different types of algorithms. Some commonly found paradigms include:
Every field of science has its own problems and needs efficient algorithms. Related problems in one field are often studied together. Some example classes are search algorithms, sorting algorithms, merge algorithms, numerical algorithms, graph algorithms, string algorithms, computational geometric algorithms, combinatorial algorithms, machine learning, cryptography, data compression algorithms and parsing techniques.
Fields tend to overlap with each other, and algorithm advances in one field may improve those of other, sometimes completely unrelated, fields. For example, dynamic programming was invented for optimization of resource consumption in industry, but is now used in solving a broad range of problems in many fields.
Algorithms can be classified by the amount of time they need to complete compared to their input size. There is a wide variety: some algorithms complete in linear time relative to input size, some do so in an exponential amount of time or even worse, and some never halt. Additionally, some problems may have multiple algorithms of differing complexity, while other problems might have no algorithms or no known efficient algorithms. There are also mappings from some problems to other problems. Owing to this, it was found to be more suitable to classify the problems themselves instead of the algorithms into equivalence classes based on the complexity of the best possible algorithms for them.
Another way to classify algorithms is by computing power. This is typically done by considering some collection (class) of algorithms. A recursive class of algorithms is one that includes algorithms for all Turing computable functions. Looking at classes of algorithms allows for the possibility of restricting the available computational resources (time and memory) used in a computation. A subrecursive class of algorithms is one in which not all Turing computable functions can be obtained. For example, the algorithms that run in polynomial time suffice for many important types of computation but do not exhaust all Turing computable functions. The class of algorithms implemented by primitive recursive functions is another subrecursive class.
Burgin (2005, p. 24) uses a generalized definition of algorithms that relaxes the common requirement that the output of the algorithm that computes a function must be determined after a finite number of steps. He defines a superrecursive class of algorithms as "a class of algorithms in which it is possible to compute functions not computable by any Turing machine" (Burgin 2005, p. 107). This is closely related to the study of methods of hypercomputation.
Algorithms, by themselves, 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" (USPTO 2006), and hence algorithms are not patentable (as in Gottschalk v. Benson). However, practical applications of algorithms are sometimes 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 highly controversial, and there are highly criticized patents involving algorithms, especially data compression algorithms, such as Unisys' LZW patent.
Additionally, some cryptographic algorithms have export restrictions (see export of cryptography).
The word algorithm comes from the name of the 9th century Persian mathematician Muhammad ibn Mūsā alKhwārizmī whose works introduced Indian numerals and algebraic concepts. He worked in Baghdad at the time when it was the centre of scientific studies and trade. The word algorism originally referred only to the rules of performing arithmetic using Arabic numerals but evolved via European Latin translation of alKhwarizmi's name into algorithm by the 18th century. The word evolved to include all definite procedures for solving problems or performing tasks.
Tallymarks: To keep track of their flocks, their sacks of grain and their money the ancients used tallying: accumulating stones or marks scratched on sticks, or making discrete symbols in clay. Through the Babylonian and Egyptian use of marks and symbols, eventually Roman numerals and the abacus evolved (Dilson, p. 16–41). Tally marks appear prominently in unary numeral system arithmetic used in Turing machine and PostTuring machine computations.
The work of the ancient Greek geometers, Persian mathematician AlKhwarizmi (often considered the "father of algebra" and from whose name the terms "algorism" and "algorithm" are derived), and Western European mathematicians culminated in Leibniz's notion of the calculus ratiocinator (ca 1680):
A good century and a half ahead of his time, Leibniz proposed an algebra of logic, an algebra that would specify the rules for manipulating logical concepts in the manner that ordinary algebra specifies the rules for manipulating numbers.^{[18]}
The clock: Bolter credits the invention of the weightdriven clock as “The key invention [of Europe in the Middle Ages]", in particular the verge escapement^{[19]} that provides us with the tick and tock of a mechanical clock. “The accurate automatic machine”^{[20]} led immediately to "mechanical automata" beginning in the thirteenth century and finally to “computational machines" – the difference engine and analytical engines of Charles Babbage and Countess Ada Lovelace.^{[21]}
Logical machines 1870  Stanley Jevons' "logical abacus" and "logical machine": The technical problem was to reduce Boolean equations when presented in a form similar to what are now known as Karnaugh maps. Jevons (1880) describes first a simple "abacus" of "slips of wood furnished with pins, contrived so that any part or class of the [logical] combinations can be picked out mechanically . . . More recently however I have reduced the system to a completely mechanical form, and have thus embodied the whole of the indirect process of inference in what may be called a Logical Machine" His machine came equipped with "certain moveable wooden rods" and "at the foot are 21 keys like those of a piano [etc] . . .". With this machine he could analyze a "syllogism or any other simple logical argument".^{[22]}
This machine he displayed in 1870 before the Fellows of the Royal Society.^{[23]} Another logician John Venn, however, in his 1881 Symbolic Logic, turned a jaundiced eye to this effort: "I have no high estimate myself of the interest or importance of what are sometimes called logical machines ... it does not seem to me that any contrivances at present known or likely to be discovered really deserve the name of logical machines"; see more at Algorithm characterizations. But not to be outdone he too presented "a plan somewhat analogous, I apprehend, to Prof. Jevon's abacus ... [And] [a]gain, corresponding to Prof. Jevons's logical machine, the following contrivance may be described. I prefer to call it merely a logicaldiagram machine ... but I suppose that it could do very completely all that can be rationally expected of any logical machine".^{[24]}
Jacquard loom, Hollerith punch cards, telegraphy and telephony — the electromechanical relay: Bell and Newell (1971) indicate that the Jacquard loom (1801), precursor to Hollerith cards (punch cards, 1887), and “telephone switching technologies” were the roots of a tree leading to the development of the first computers.^{[25]} By the mid1800s the telegraph, the precursor of the telephone, was in use throughout the world, its discrete and distinguishable encoding of letters as “dots and dashes” a common sound. By the late 1800s the ticker tape (ca 1870s) was in use, as was the use of Hollerith cards in the 1890 U.S. census. Then came the Teletype (ca. 1910) with its punchedpaper use of Baudot code on tape.
Telephoneswitching networks of electromechanical relays (invented 1835) was behind the work of George Stibitz (1937), the inventor of the digital adding device. As he worked in Bell Laboratories, he observed the “burdensome’ use of mechanical calculators with gears. "He went home one evening in 1937 intending to test his idea... When the tinkering was over, Stibitz had constructed a binary adding device".^{[26]}
Davis (2000) observes the particular importance of the electromechanical relay (with its two "binary states" open and closed):
Symbols and rules: In rapid succession the mathematics of George Boole (1847, 1854), Gottlob Frege (1879), and Giuseppe Peano (1888–1889) reduced arithmetic to a sequence of symbols manipulated by rules. Peano's The principles of arithmetic, presented by a new method (1888) was "the first attempt at an axiomatization of mathematics in a symbolic language"^{[28]}.
But Heijenoort gives Frege (1879) this kudos: Frege’s is "perhaps the most important single work ever written in logic. ... in which we see a " 'formula language', that is a lingua characterica, a language written with special symbols, "for pure thought", that is, free from rhetorical embellishments ... constructed from specific symbols that are manipulated according to definite rules"^{[29]}. The work of Frege was further simplified and amplified by Alfred North Whitehead and Bertrand Russell in their Principia Mathematica (1910–1913).
The paradoxes: At the same time a number of disturbing paradoxes appeared in the literature, in particular the BuraliForti paradox (1897), the Russell paradox (1902–03), and the Richard Paradox^{[30]}. The resultant considerations led to Kurt Gödel’s paper (1931) — he specifically cites the paradox of the liar — that completely reduces rules of recursion to numbers.
Effective calculability: In an effort to solve the Entscheidungsproblem defined precisely by Hilbert in 1928, mathematicians first set about to define what was meant by an "effective method" or "effective calculation" or "effective calculability" (i.e., a calculation that would succeed). In rapid succession the following appeared: Alonzo Church, Stephen Kleene and J.B. Rosser's λcalculus^{[31]} a finelyhoned definition of "general recursion" from the work of Gödel acting on suggestions of Jacques Herbrand (cf. Gödel's Princeton lectures of 1934) and subsequent simplifications by Kleene^{[32]}. Church's proof^{[33]} that the Entscheidungsproblem was unsolvable, Emil Post's definition of effective calculability as a worker mindlessly following a list of instructions to move left or right through a sequence of rooms and while there either mark or erase a paper or observe the paper and make a yesno decision about the next instruction^{[34]}. Alan Turing's proof of that the Entscheidungsproblem was unsolvable by use of his "a [automatic] machine"^{[35]}  in effect almost identical to Post's "formulation", J. Barkley Rosser's definition of "effective method" in terms of "a machine"^{[36]}. S. C. Kleene's proposal of a precursor to "Church thesis" that he called "Thesis I"^{[37]}, and a few years later Kleene's renaming his Thesis "Church's Thesis"^{[38]} and proposing "Turing's Thesis"^{[39]}.
Here is a remarkable coincidence of two men not knowing each other but describing a process of menascomputers working on computations — and they yield virtually identical definitions.
Emil Post (1936) described the actions of a "computer" (human being) as follows:
His symbol space would be
Alan Turing’s work^{[41]} preceded that of Stibitz (1937); it is unknown whether Stibitz knew of the work of Turing. Turing’s biographer believed that Turing’s use of a typewriterlike model derived from a youthful interest: “Alan had dreamt of inventing typewriters as a boy; Mrs. Turing had a typewriter; and he could well have begun by asking himself what was meant by calling a typewriter 'mechanical'"^{[42]}. Given the prevalence of Morse code and telegraphy, ticker tape machines, and Teletypes we might conjecture that all were influences.
Turing — his model of computation is now called a Turing machine — begins, as did Post, with an analysis of a human computer that he whittles down to a simple set of basic motions and "states of mind". But he continues a step further and creates a machine as a model of computation of numbers^{[43]}.
Turing's reduction yields the following:
"It may be that some of these change necessarily invoke a change of state of mind. The most general single operation must therefore be taken to be one of the following:
A few years later, Turing expanded his analysis (thesis, definition) with this forceful expression of it:
J. Barkley Rosser boldly defined an ‘effective [mathematical] method’ in the following manner (boldface added):
Rosser's footnote #5 references the work of (1) Church and Kleene and their definition of λdefinability, in particular Church's use of it in his An Unsolvable Problem of Elementary Number Theory (1936); (2) Herbrand and Gödel and their use of recursion in particular Gödel's use in his famous paper On Formally Undecidable Propositions of Principia Mathematica and Related Systems I (1931); and (3) Post (1936) and Turing (19367) in their mechanismmodels of computation.
Stephen C. Kleene defined as his nowfamous "Thesis I" known as the ChurchTuring thesis. But he did this in the following context (boldface in original):
A number of efforts have been directed toward further refinement of the definition of "algorithm", and activity is ongoing because of issues surrounding, in particular, foundations of mathematics (especially the ChurchTuring Thesis) and philosophy of mind (especially arguments around artificial intelligence). For more, see Algorithm characterizations.
An algorithm is a step by step list of directions that need to be followed to solve a problem. The instructions should be simple enough so that each step can be done without thinking about it. Algorithms are often used to describe how a computer might solve a problem. But there are algorithms in the real world too. A recipe can be a type of algorithm. It tells what ingredients are needed to make the dish and what steps to follow. If the recipe tells exactly what to do without too much confusion, then it is an algorithm.
Contents 
There is usually more than one way to solve a problem; there may be many different recipes to make a certain dish which look different but end up tasting the same when all is said and done. The same is true for algorithms. However, some of these ways will be better than others. If a recipe needs lots of complicated ingredients that you do not have, it is not as a good as a simple recipe. When we look at algorithms as a way of solving problems, often we want to know how long it would take a computer to solve the problem using a particular algorithm. When we write algorithms, we like our algorithm to take the least amount of time so that we can solve our problem as quickly as possible.
In cooking, some recipes are more difficult to do than others, because they take more time to finish or have more things to keep track of. It's the same for algorithms, and algorithms are better when they are easier for the computer to do. The thing that measures how hard an algorithm is; is called complexity. When we ask how complex an algorithm is, often we want to know how long it will take a computer to solve the problem we want it to solve.
This is an example of an algorithm for sorting cards with colors on them into piles of the same color:
These are examples of algorithms for sorting a stack of cards with many different numbers, so that the numbers are in order.
Players start with a stack of cards that have not been sorted
This algorithm goes through the stack of cards, one card at a time; this card is compared to the next card in the stack. Please note that this position only changes in step 3. This algorithm is called bubble sort. It is slow.
Let us take a stack of the cards with the numbers "5 1 4 2 8", and sort it from smallest number to biggest one using this algorithm. In each step, the algorithm compares the elements written in bold. The top of the stack of cards is on the left hand side.
First Pass:
( 5 1 4 2 8 ) $\backslash to$ ( 1 5 4 2 8 ) Here, the algorithm compares the first two elements, and swaps them.
( 1 4 5 2 8 ) $\backslash to$ ( 1 4 2 5 8 )
( 1 4 2 5 8 ) $\backslash to$ ( 1 4 2 5 8 ) These elements are already in order, so the algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) $\backslash to$ ( 1 4 2 5 8 )
( 1 4 2 5 8 ) $\backslash to$ ( 1 2 4 5 8 )
( 1 2 4 5 8 ) $\backslash to$ ( 1 2 4 5 8 )
( 1 2 4 5 8 ) $\backslash to$ ( 1 2 4 5 8 )
Now, the stack of cards is already sorted, but our algorithm does not know this. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) $\backslash to$ ( 1 2 4 5 8 )
( 1 2 4 5 8 ) $\backslash to$ ( 1 2 4 5 8 )
( 1 2 4 5 8 ) $\backslash to$ ( 1 2 4 5 8 )
( 1 2 4 5 8 ) $\backslash to$ ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can stop.
This is a easy to understand algorithm for sorting. Computer scientists called it Bubble sort, because smaller elements will rise to the top, changing their position in each run. Unfortunately, the algorithm is not very good, because it needs a long time (many passes through the stack of cards) to sort it.
This algorithm uses another idea. Sometimes solving a problem is difficult, but the problem can be changed so it is made of simpler problems, that are easier to solve. This is called recursion. It is more difficult to understand than the first example, but it will give a better algorithm.
This works with two stacks of cards, one of them is called A, the other is called B. There is a third stack that is empty at the start, called C. At the end, it will contain the result.
John von Neumann developed this algorithm in 1945. He didn't call it Sorting by numbers, he called it Mergesort. It is a very good algorithm for sorting, compared to others.
The first algorithm takes much longer to sort the cards than the second, but it can be improved (made better). Looking at bubble sort, it can be noticed that cards with high numbers move from the top of the stack quite quickly, but cards with low numbers, at the bottom of the stack take a long time to rise (move to the top). To improve the first algorithm here is the idea:
This algorithm was developed by C. A. R. Hoare in 1960. It is one of most widely used algorithms for sorting today. It is called Quicksort
If players have cards with colors and numbers on them, they can sort them by color and number if they do the "sorting by colors" algorithm, then do the "sorting by numbers" algorithm to each colored stack, then put the stacks together.
The sorting by numbers algorithms are more difficult to do than the sorting by colors algorithm, because they may have to do the steps again many times. One would say that sorting by numbers is more complex.
