About this book
The Art of Computer Programming, Volume 1: Fundamental Algorithms appeared from Addison-Wesley in 1968. Its author, Donald E. Knuth, was then a young mathematician who had been asked, some years earlier, to write a single book about compilers. The book he actually wrote grew into something much larger: a planned series of volumes that would set out, with full mathematical care, the core techniques of programming as they were then known. Volume 1 is the foundation of that series. It is the volume that every later one assumes.
The situation in which it was written matters. In the early 1960s programming was a craft learned on the job. Programs were written for particular machines, techniques passed from person to person, and published results were scattered across conference papers, company manuals and the private notes of working programmers. There was no agreed body of knowledge, and there was very little understanding of how to say precisely how good a program was. Knuth set out to gather what was known, test it, put it in order, and give it a mathematical backbone.
The book is written for two kinds of reader at once. One is the working programmer who wants to know the best way to do a common task and why it is best. The other is the mathematician or student who wants to see programs treated as objects that can be reasoned about exactly. Knuth does not separate these readers into different books. He writes one text in which practical advice and proof sit side by side, and he marks the harder mathematical parts so that a reader can skip them without losing the thread.
The central question of Volume 1 can be put simply. It asks what it means to understand an algorithm. Knuth's answer has three parts. You must know exactly what the procedure does, step by step. You must be able to show that it does what it claims. And you must be able to say how much it costs, in time and in memory, not roughly but as precisely as the mathematics allows. The first half of the volume builds the tools for this kind of understanding. The second half applies them to the basic ways of arranging information inside a computer.
Volume 1 therefore has two large chapters. The first deals with basic concepts: what an algorithm is, the mathematics needed to analyse one, an imaginary computer called MIX on which programs are written, and some fundamental programming techniques. The second deals with information structures: lists, stacks, queues, trees, and the problem of managing memory while a program runs. Each section ends with exercises, graded for difficulty, and the answers fill a large part of the book.
It is worth being clear about what kind of book this is. It is not an introduction to programming in a particular language. It is not a survey of all useful algorithms. It is not a quick reference. It is closer to a treatise, in the old sense: a long, ordered, careful exposition of a subject by someone trying to get every detail right. The shelf note puts it in a phrase. These are algorithms analysed down to the instruction count, and the work is still being written.
The author
Donald Ervin Knuth was born in 1938 in Milwaukee, Wisconsin. His father taught and ran a small printing business, a detail that later mattered. As a student at the Case Institute of Technology in Cleveland he moved from physics into mathematics, and he discovered computers through an IBM 650, one of the early commercial machines. He wrote programs for it, studied the code of others, and found that he loved the work. He took a doctorate in mathematics at the California Institute of Technology in 1963, in combinatorics, and stayed on to teach there.
While still a graduate student he signed a contract with Addison-Wesley to write a book on compilers. He wrote by hand, and the draft swelled. By the mid-1960s he had thousands of pages, far too much for one book, and much of it was not about compilers at all but about the techniques that compilers and every other program rely on. Knuth and his publisher agreed to reorganise the material as a series of seven volumes. Volume 1 appeared in 1968, Volume 2 on seminumerical algorithms in 1969, and Volume 3 on sorting and searching in 1973. Knuth moved to Stanford University at the end of the decade, where he remained for the rest of his career.
In 1974 he received the Turing Award, the highest honour in computer science, largely for this work and for founding the systematic analysis of algorithms. He is usually credited with coining that phrase, analysis of algorithms, for the field his books helped to define. In the mid-1970s he also wrote a short paper that fixed the modern meanings of the notations used to describe the growth of functions, the big-O family, so that computer scientists would use them consistently.
The series then took an unexpected turn. When a new edition of Volume 2 was being prepared in the 1970s, the typesetting technology of the day produced pages Knuth found ugly. He decided to fix the problem himself. The result, after about a decade of work, was TeX, a typesetting system, and METAFONT, a system for designing type. TeX became the standard tool for typesetting mathematics across the world. It is one of the reasons the later editions of the series look the way they do. The printer's son had, in a sense, gone back to the family trade.
Out of the work on TeX came another idea, literate programming. Knuth argued that a program should be written as a document meant for human readers, with code and explanation woven together, and he built tools to support this. The same instinct runs through The Art of Computer Programming. Knuth always writes as if the reader deserves a full explanation, and he always treats exposition as part of the work, not decoration added afterwards.
With Ronald Graham and Oren Patashnik he wrote Concrete Mathematics, a textbook that grew from a Stanford course and expands the mathematical preliminaries of Volume 1 into a full book. He revised Volume 1 for a second edition in the 1970s and a third edition in 1997. He retired early from teaching to devote himself to finishing the series, and he has continued to issue the long-delayed Volume 4, on combinatorial algorithms, in parts and fascicles, with Volume 4A appearing in 2011 and 4B in 2022. Volume 5 and beyond remain in progress.
Knuth is famous for his care about errors. He has long offered a small cheque, traditionally 2.56 dollars, one hexadecimal dollar, to the first person to report each error in his books. Many recipients frame the cheques rather than cash them. The practice says something about the book. It is meant to be correct in every detail, and its author treats each mistake as a debt.
The shape of the argument
Volume 1 moves from the general to the particular and from tools to applications. It begins with a definition, builds a mathematical toolkit, constructs a machine, teaches techniques for using that machine, and then turns to the structures that programs build in memory. Each stage depends on those before it, and the reader is expected to carry everything forward.
The first movement is conceptual. Knuth asks what an algorithm is, and his answer is careful because everything later depends on it. He illustrates the definition with one of the oldest algorithms known, Euclid's method for finding the greatest common divisor of two numbers, and uses it to show what it means to prove that a procedure is correct. This is the seed of the whole series: a small, exact procedure, examined from every side.
The second movement is mathematical, and it is the part many readers remember with a mixture of awe and dread. Knuth gathers the mathematics that the analysis of algorithms requires: induction, sums and products, integer functions such as floor and ceiling, elementary number theory, permutations, binomial coefficients, harmonic numbers, Fibonacci numbers, generating functions and asymptotic methods. He presents these not as a course in pure mathematics but as a working kit. Each tool is chosen because it will be needed to count the steps of some program.
The third movement is mechanical. Knuth introduces MIX, an imaginary computer, and its assembly language. He explains why he chose to describe programs at this low level rather than in a high-level language, and he then teaches a set of basic programming techniques on this machine, including subroutines, coroutines, interpreters and the handling of input and output. This part makes the costs of programs visible. Every instruction can be counted, and every memory cell can be accounted for.
The fourth movement, which fills the second chapter, is structural. Here Knuth turns to the ways information is arranged inside a machine. He begins with simple linear lists and the operations on them, moves to linked structures in which items point to one another, then to trees, then to structures with many links, and finally to the problem of allocating and reclaiming memory dynamically. At each stage he gives algorithms, programs in MIX, analyses of cost, and historical notes.
Running underneath all four movements is a single method. State the algorithm precisely. Prove it correct. Implement it on a concrete machine. Count what it costs. Compare it with alternatives. Trace its history. The method is applied to small examples and to large ones with the same patience. A reader who absorbs this method has gained more than any single algorithm in the book.
The exercises are part of the argument, not an appendix to it. Many important results appear only in the exercises and their answers. Knuth grades each exercise on a scale from trivial to unsolved research problem, and he marks those that need mathematics beyond the ordinary. The book is designed to be worked, not only read. A large share of what it teaches is found by doing.
What an algorithm is
Everyone who has followed a recipe has followed something like an algorithm. But a recipe usually leaves a great deal to the cook. It says season to taste, or cook until done. An algorithm, in Knuth's sense, cannot leave anything to taste. It must be stated so exactly that it can be carried out mechanically, by someone or something with no judgment at all.
Knuth lists five properties that an algorithm must have. It must be finite: it must always stop after a finite number of steps. It must be definite: each step must be stated precisely and without ambiguity. It must have input: zero or more quantities given to it before it begins. It must have output: one or more quantities related to the input. And it must be effective: each operation must be basic enough that it could, in principle, be done exactly by a person with pencil and paper in a finite time.
Each of these conditions excludes something familiar. Finiteness excludes procedures that may run forever, which Knuth calls computational methods rather than algorithms. An operating system that waits for commands indefinitely is a computational method in this sense. Definiteness excludes ordinary language instructions that two readers might understand differently. Effectiveness excludes steps such as take the exact value of an infinite decimal, which no finite worker could carry out.
The point of being so careful is that it makes proof possible. Once a procedure is stated exactly, one can ask exact questions about it. One can ask whether it always stops and whether it always gives the right answer. Knuth shows how to answer such questions with the method of assertions. At each point in the procedure one writes down a statement that is true whenever control reaches that point. If each step preserves the truth of these statements, and if the procedure terminates, then the final statement is guaranteed. This idea, in various forms, became the basis of program verification.
An analogy may help. Think of a long journey on foot, with a checkpoint at each town. At each checkpoint an inspector confirms that the traveller still carries everything required. If every leg of the journey begins with the requirements met and ends with them met, the traveller will arrive with everything required. Assertions are those checkpoints. Proving a program correct is showing that no leg of the journey loses anything.
Knuth's chosen example, Euclid's algorithm, is perfect for this purpose. It is short, it is ancient, it is genuinely useful, and its correctness is not obvious at first sight. That repeatedly replacing a pair of numbers by the smaller one and the remainder leads to their greatest common divisor needs explaining. The explanation requires a small piece of number theory and a careful argument about termination. In a few pages the reader sees the whole cycle: statement, proof, and a first question about cost, since one can ask how many steps the procedure takes.
The definition is often confused with the looser modern use of the word. Today people speak of the algorithm of a social network or a search engine, meaning a large system whose behaviour is opaque and changes over time. That usage is not wrong, but it is not Knuth's. His algorithm is small enough to state, exact enough to prove, and fixed enough to analyse. The gap between these two meanings is itself instructive. Much of the difficulty of modern software lies in systems that are no longer algorithms in his strict sense.
The definition also leads somewhere important. Once algorithms are exact objects, they can be compared. Two procedures that solve the same problem can be set side by side and asked which uses fewer steps, which uses less memory, which behaves better on typical inputs and which on the worst. The definition of an algorithm is thus the gateway to the analysis of algorithms, the field Knuth did most to found.
Counting exactly: the analysis of algorithms
Before Knuth, the cost of a program was usually judged by trying it. One ran it on some examples and measured how long it took. This tells you something, but not much. It depends on the machine, the examples chosen, and many accidents. Knuth wanted something better: a mathematical account of how the cost of an algorithm depends on its input.
His method is direct. For each step of an algorithm, count how many times it is executed. These counts depend on the input. Some are fixed; some depend on the size of the input; some depend on the particular arrangement of the data. Then multiply each count by the cost of the step, add everything up, and you have the total running time as a formula. The formula can be studied for its best case, its worst case and, most interestingly, its average case over all possible inputs.
Consider a simple task, finding the largest number in a list. Every number must be looked at once, so that part of the cost is fixed. But there is a step that runs only when a new largest value is found, when the current champion is replaced. The number of such replacements varies. In the worst case, when the list is in increasing order, it happens every time. In the best case, when the largest number comes first, it never happens. On average, if all orders are equally likely, it happens about as often as the harmonic number of the list's length, which grows like the natural logarithm. A question that looked trivial leads straight to a classical piece of mathematics. Knuth uses an example of exactly this kind to show what analysis means.
This is why the mathematical preliminaries are in the book. Counting the steps of real algorithms produces sums that must be evaluated, recurrences that must be solved, and probabilities that must be computed. Harmonic numbers turn up when one asks how often something changes. Binomial coefficients turn up when one counts arrangements. Fibonacci numbers turn up in the analysis of Euclid's algorithm itself. Generating functions, which encode a whole sequence of numbers as the coefficients of a single function, turn out to be one of the strongest tools for solving the recurrences that algorithms produce.
The analysis of algorithms is often confused with complexity theory, and the difference is worth keeping straight. Complexity theory, the subject of books such as Garey and Johnson's Computers and Intractability on this shelf, asks how hard a problem is, meaning the least cost of any algorithm that solves it. It usually works with coarse measures, such as whether the cost grows polynomially or exponentially. Knuth's analysis asks how much a particular algorithm costs, and it seeks exact answers, including constant factors and lower-order terms. The two are complementary. Complexity theory tells you which problems are feasible. Analysis tells you which of several feasible methods to use and what to expect from it.
Knuth also cared about asymptotic notation, the shorthand for describing how a quantity grows. Writing that a cost is of order n squared hides constants and smaller terms, which is useful when one wants the big picture. But Knuth was careful to say what such statements mean, and he insisted that they be used precisely. Much confusion in casual discussion of algorithms comes from treating these notations loosely, for example by reading an upper bound as if it were an exact rate.
The deeper lesson is a habit of mind. When you meet a procedure, do not be content with the feeling that it is fast or slow. Ask how many times each part runs, and on what that depends. The answer often surprises. Programs that look expensive can be cheap on typical inputs, and programs that look cheap can hide an operation that runs far more often than expected. Exact counting replaces impressions with knowledge.
This programme leads into a whole branch of mathematics. Later researchers, notably Robert Sedgewick and Philippe Flajolet, developed analytic combinatorics, a systematic theory for the kinds of counting problems Knuth's analyses raise. Their work grew directly from the programme this volume set out. The idea that programs are mathematical objects with exact, provable costs has proved to be one of the most fertile in computer science.
The machine on the page: MIX
The most debated decision in the book is Knuth's choice to present programs in the assembly language of an imaginary computer. MIX is not a real machine. Knuth designed it to resemble the computers of the 1960s, to be simple enough to learn quickly, and to be general enough that programs written for it could be translated to most real machines. Its name, he notes playfully, is the Roman numeral for 1009, which he arrived at as a rough average of the model numbers of contemporary computers.
MIX has a handful of registers, small fast storage locations inside the processor: an accumulator for arithmetic, an extension register, six index registers used for counting and addressing, and a jump register that remembers where to return after a subroutine call. It has a memory of a few thousand words. Its instructions load and store values, do arithmetic, compare, jump and perform input and output. Each instruction has a stated cost in time units, so that a program's running time can be computed exactly.
One clever feature deserves mention. Knuth left the size of a MIX byte deliberately unspecified, within limits, so that a byte might hold anywhere from 64 to 100 distinct values. A machine of the first kind behaves like a binary computer and one of the second like a decimal computer. A correct MIX program must work on both. This forces the programmer to write code that does not depend on accidents of representation, a discipline that carries over to real work.
Knuth gives several reasons for avoiding a high-level language. High-level languages come and go, and a book meant to last decades should not be tied to one. More importantly, a high-level language hides the costs that Knuth wants to analyse. A single line can conceal a loop, a memory allocation or a subroutine call. To count operations honestly, one must see them. Assembly language shows everything. A further reason is that many important techniques, such as coroutines and certain ways of managing memory, are most naturally expressed close to the machine.
The decision has costs, and Knuth knew it. Assembly code is hard to read, and many readers skip the MIX programs and work only from the step-by-step algorithm descriptions, which Knuth gives in a structured English before each program. That is a reasonable way to read the book on a first pass. The algorithms are complete without the programs. But the programs are where the exact counts come from, and a reader who wants the full analysis must eventually engage with them.
By the 1990s MIX had become dated. Real machines had moved to binary arithmetic, larger registers and simpler instruction sets of the kind described in Hennessy and Patterson's Computer Architecture, which sits in the same bay. Knuth designed a successor, MMIX, a 64-bit machine in the modern style, and announced that future editions would use it. He published a fascicle describing MMIX, and others have translated the programs of the first volumes into its language. For now the printed Volume 1 still uses MIX.
It is easy to misread the role of MIX. It is not a claim that everyone should program in assembly language. It is a measuring instrument. In the same way that a physicist uses an idealised frictionless surface to make the forces in a problem visible, Knuth uses an idealised machine to make the costs of an algorithm visible. Once the analysis is done, its conclusions apply to programs written in any language on any reasonable machine, with adjustments to the constants.
There is also a teaching point. A programmer who has written even a few programs in MIX, or any assembly language, understands something that pure high-level programming hides: that data lives at addresses, that a pointer is just a number naming a location, that a subroutine call is a jump and a saved return address. Charles Petzold's Code, also on this shelf, makes the same journey from the other end, building up from switches and circuits. Together they show the machine beneath the abstraction.
Techniques close to the machine
Between the machine and the data structures, Knuth places a section on fundamental programming techniques. It is short compared with the rest of the volume, but it contains ideas that are still central and that many programmers today know only in disguised form.
Subroutines
A subroutine is a piece of code written once and called from many places. Today it would be called a function or procedure, and every language supports it directly. Knuth shows what lies underneath: how the return address is saved, how parameters are passed, how a subroutine can be written so that it does not disturb the registers its caller relies on. He also discusses the trade-offs. Calling a subroutine costs time, and a very small piece of code may be better repeated than called. Seeing these costs at the machine level makes clear why later language designers made the choices they did.
Coroutines
A coroutine is a less familiar idea, and Knuth's treatment of it is one of the clearest anywhere. An ordinary subroutine has a master and a servant: the caller calls, the subroutine runs to completion and returns. Two coroutines are equals. Each runs for a while, then passes control to the other, which resumes exactly where it left off. Neither is master. The classic use is a pipeline, in which one routine produces items and another consumes them, each written as if it were the main program. Many modern features, such as generators, async functions and cooperative threads, are coroutines under other names. A reader who learns the idea here will recognise it everywhere.
Interpreters and simulators
An interpretive routine is a program that reads instructions written in some other language and carries them out. Knuth discusses interpreters in general and includes, as an extended example, a program that simulates MIX itself on MIX. This idea, a machine imitating a machine, is one of the deepest in computing. It is the practical side of the universality that Turing described in theory, and which the papers collected in The Undecidable explore. Every virtual machine and emulator used today rests on it.
Input and output
Knuth also treats input and output, including the technique of buffering, in which data is moved in blocks while the processor continues other work. The specific devices he discusses, such as tape units and card readers, are long gone. The underlying problem is not. Any program that talks to a slower device, a disk or a network, faces the same question of how to keep the fast part busy while waiting on the slow part. The solutions he describes reappear in every operating system.
What unites these techniques is a concern with control: who is running, where they will return, what state must be saved and restored. High-level languages handle much of this automatically, which is a great convenience. But when something goes wrong, or when performance matters, the programmer must understand what is being handled. This section is where Volume 1 teaches that understanding.
Lists, stacks and queues
The second chapter of the volume begins with the simplest way to organise data: a linear list, a sequence of items one after another. A shopping list, a queue at a counter and a pile of plates are all linear lists. What distinguishes them is not the items but the operations allowed. Knuth's insight, now standard, is that a data structure is defined as much by what you may do with it as by how it is stored.
A stack allows items to be added and removed only at one end, so the last item in is the first out. A queue adds at one end and removes at the other, so the first in is the first out. A deque, a double-ended queue, allows additions and removals at both ends. These three restricted lists turn up constantly. Stacks manage subroutine calls and the evaluation of expressions. Queues manage tasks waiting for service. The restrictions are not limitations to be regretted. They are what make these structures simple, fast and easy to reason about.
Knuth then distinguishes two ways of storing a list. Sequential allocation places items in consecutive memory locations, like houses numbered in order along a street. It is compact and allows quick access to any item by position, but inserting or deleting in the middle means shifting everything after it. Linked allocation stores each item with a pointer to the next, like a treasure hunt in which each clue says where to find the following one. Inserting or deleting is cheap, just change a pointer or two, but finding the hundredth item means following a hundred links.
The trade-off between these two is one of the permanent themes of programming. Every modern language library offers both kinds of list, and the choice between them is still made by the same reasoning Knuth sets out. He goes further than most textbooks by analysing what happens when several sequential lists must share one block of memory and grow at different rates, a problem that requires periodically repacking the lists and that leads to a pleasing piece of analysis about how often such repacking is needed.
Among the algorithms in this part, one stands out: topological sorting. Suppose you have a set of tasks, and some must be done before others. Getting dressed is a homely example: socks before shoes, shirt before tie. A topological sort puts the tasks in an order that respects every such constraint. Knuth's algorithm for it uses a clever combination of counts and linked lists and runs in time proportional to the number of tasks plus the number of constraints. Build systems, spreadsheet recalculation and course prerequisite planning all solve this problem.
Knuth also treats circular lists, in which the last item points back to the first, and doubly linked lists, in which each item points both forward and back. Each variation buys some convenience at some cost in memory or complexity. He shows, for example, how a circular list makes certain operations, such as joining two lists, take constant time. The examples include arithmetic on polynomials represented as linked lists, a nice demonstration of how the right structure makes an algebraic operation almost mechanical.
Finally he considers arrays and orthogonal lists, structures in which items are linked in two or more directions at once, as in a sparse matrix where most entries are zero and only the nonzero ones are stored, each linked to its neighbours in its row and column. This prepares the ground for the more elaborate structures that follow.
What is often missed in reading this material is how much of it is about invariants, the conditions that remain true while a structure changes. A linked list is correct only if every pointer leads where it should. Each operation must preserve that. The method of assertions from the first chapter here becomes practical. One thinks about a data structure by stating what must always be true of it and then checking that each operation keeps it so.
Trees and the shape of information
A tree is a structure in which each item, called a node, may have several children, and each node except one, the root, has exactly one parent. Family trees, the outline of a book, the folders on a disk and the structure of a sentence are all trees. They are the natural way to represent anything hierarchical, and Knuth devotes the longest section of the volume to them.
He begins with definitions and the vocabulary that has since become standard: root, subtree, leaf, level, degree, forest. He distinguishes ordinary trees, in which a node may have any number of children, from binary trees, in which each node has at most a left and a right child, and these two are treated as different kinds of object. He then shows a correspondence between them. Any forest of ordinary trees can be represented as a binary tree by a simple rule: link each node to its first child and to its next sibling. This correspondence means that algorithms for binary trees can handle general trees as well.
Traversal is the problem of visiting every node of a tree in some systematic order. Knuth describes the standard orders, in which a node is visited before its subtrees, between them or after them, and he gives algorithms for each, first using a stack and then using a clever technique called threading, in which the otherwise empty links of a binary tree are made to point to the next node in a traversal order. Threaded trees can be traversed without any extra storage. The idea is a lovely example of using space that would otherwise be wasted.
The mathematical properties of trees receive full treatment. The number of different binary trees with a given number of nodes is given by the Catalan numbers, a sequence that turns up in many counting problems. Knuth also studies the paths through a tree and their average length. Such questions matter because the cost of many algorithms is the length of a path in some tree. Knuth also discusses the remarkable theorem that counts the number of trees that can be formed on a set of labelled points, and he relates trees to graphs more generally.
An example helps fix the idea. Consider the arithmetic expression a plus b times c. As written, it is a string of symbols. As a tree, it has a plus at the root, a on the left, and on the right a times node with b and c below it. The tree makes the structure explicit: it shows that multiplication is done first. Traversing the tree in one order gives back the ordinary expression. Traversing it in another gives the form used by stack-based calculators, in which operators follow their operands. Compilers, of the kind described in Aho, Sethi and Ullman's Compilers on this shelf, work largely by building and walking such trees.
Knuth closes this section with lists in a more general sense, structures that may contain other lists and may even share parts or contain themselves. These are the structures used by languages such as Lisp. With them comes the problem of garbage collection: when parts of a structure are no longer reachable from the running program, the system must find and reclaim them. Knuth explains the basic marking methods and an elegant algorithm for marking that uses almost no extra memory by temporarily reversing pointers as it goes. Garbage collection, then a specialist concern, is now built into most widely used languages.
A common confusion is to think of trees only as a way to store data for searching, as in the binary search trees taught in many courses. Searching with trees belongs mainly to Volume 3. Volume 1 is concerned with trees as a general form of information, the shape of hierarchical data, and with the fundamental operations and counting results that apply to all of them. Its treatment is broader and more basic than the search-tree material many readers meet first.
Managing memory while a program runs
The last major topic of the volume is dynamic storage allocation. A running program often needs blocks of memory of varying sizes, uses them for a while, and then releases them. The system must keep track of which parts of memory are free, find a suitable block when one is requested, and take back blocks when they are released. This sounds simple. It is one of the hardest problems in systems programming.
The central difficulty is fragmentation. Imagine a long shelf on which books of different widths are placed and removed over time. After a while the free space is broken into many small gaps, none wide enough for a large new book, even though the total free space would be ample if it were in one piece. Memory behaves the same way. An allocation method must try to avoid leaving useless fragments, and it must do so quickly, because allocation happens constantly.
Knuth examines several methods. First-fit takes the first free block large enough for the request. Best-fit searches for the free block whose size is closest to the request, on the theory that this wastes least. Intuition suggests best-fit should be better, but Knuth reports simulations showing that first-fit often does as well or better, because best-fit tends to leave many tiny unusable fragments. This is a good example of the book's general lesson: intuition about algorithms is unreliable, and careful measurement or analysis is needed.
He also describes the boundary-tag method, in which each block records its size and status at both ends, so that when a block is freed it can be merged quickly with free neighbours on either side. And he describes the buddy system, in which memory is split into blocks whose sizes are powers of two. Each block has a unique buddy of the same size, found by a simple arithmetic rule, and when both buddies are free they are combined. The buddy system is fast and simple, at some cost in wasted space because requests must be rounded up to a power of two.
Knuth adds a cautionary note that has aged well. Analysis of these methods is difficult, and simulations show that behaviour depends heavily on the pattern of requests. No method is best in all circumstances. Modern memory allocators in operating systems and language runtimes are elaborate combinations of these basic ideas, tuned for common patterns, and the debates about them continue. The vocabulary of that debate, fragmentation, coalescing, first-fit, buddy, comes largely from this section.
This topic is often confused with garbage collection, though the two are related. Allocation is about handing out and taking back memory when the program says it is done. Garbage collection is about discovering, without being told, which memory is no longer in use. A system may need both. Knuth treats them in separate places because they are separate problems, and keeping them apart helps one think clearly about each.
Exercises and the habit of working
No account of Volume 1 is complete without its exercises. There are hundreds of them, and the answers occupy roughly a quarter of the book. Each exercise carries a rating number. A rating near zero means the exercise is a quick check; around ten, a minute or so of thought; around twenty, perhaps a quarter of an hour; around thirty, hours of work; around forty, a term project; and around fifty, an unsolved research problem. Knuth also marks exercises that require mathematical knowledge, those that need higher mathematics such as calculus, and those he especially recommends.
The rating system is a small piece of educational design that deserves imitation. It lets the reader choose a path. A student may work every exercise rated twenty or below. A researcher may go straight to the hard ones. A casual reader may read the easy ones and their answers as a way of checking understanding. The scale also sets honest expectations. An exercise rated thirty-five should not discourage someone who cannot do it in an evening.
Many exercises contain real content. Results that would interrupt the flow of the main text are placed in exercises, so that the text stays focused while the reader who wants more can find it. The answers are not just solutions. They often extend the discussion, give historical notes or point to further work. Reading the answer section as a book in itself is a good way to discover how much the volume contains.
There is a broader lesson here about how technical knowledge is acquired. Reading about an algorithm gives a feeling of understanding that often does not survive the first attempt to use it. Working an exercise tests the feeling. Knuth's book is built on the belief that understanding comes from doing, and its structure forces the reader to do. This is one reason the book is slow to read and one reason its readers remember it.
The habit Knuth teaches is concrete. When you meet a claim, check it on a small case. When you meet an algorithm, run it by hand on a tiny input and watch every variable. When you meet a formula, test it with the first few values. These checks are tedious, and they catch most errors. They are also the way to build the intuition that later lets you work faster.
History as part of the subject
Each major section of the volume ends with historical notes, and these are not a courtesy. Knuth treats the history of an idea as part of understanding it. He traces who first described a technique, how it was rediscovered or improved, and what confusion surrounded it. He was one of the first computer scientists to take the history of the field seriously, and he did so while the field was young enough that many of its founders could still be consulted.
His notes reach far back. Euclid's algorithm is more than two thousand years old. Ancient and medieval mathematicians in many cultures described step-by-step procedures, and Knuth has written elsewhere about early algorithms, including Babylonian procedures recorded on clay tablets. The word algorithm itself comes from the name of the ninth-century Persian mathematician al-Khwarizmi, whose book on calculation with Hindu numerals spread decimal arithmetic to Europe. Knuth discusses this origin. The reader learns that programming is a modern form of a very old human activity.
For the modern period, the notes record the work of early programmers, many of whom never published in conventional journals. Techniques such as linked lists, stacks and subroutines emerged in the late 1940s and 1950s among the people building and programming the first machines, including the group around John von Neumann whose story George Dyson tells in Turing's Cathedral on this shelf. Knuth's notes give credit carefully and often correct earlier attributions.
This matters for a reader today partly because history shows that ideas which now seem obvious were once hard won, and that is good for humility. Partly because it shows how ideas recur. Coroutines, for example, were described in the 1960s, fell out of fashion, and returned decades later under new names. A reader who knows the history recognises old ideas in new clothes and can draw on what was learned the first time.
The tradition around it
Volume 1 stands at a crossing point. Behind it lie the founders of computing: Babbage's plans for a mechanical engine, recounted in his Passages from the Life of a Philosopher; the theory of computation set out by Turing, Church and others, collected in The Undecidable; and the stored-program design of von Neumann, whose late reflections appear in The Computer and the Brain. Those works asked what a computer could be and what it could do in principle. Knuth's book asks a more practical and more detailed question: given such a machine, how to make it do things well, and how to know that it does.
Around the same time, other people were working on making programs reliable. Structured Programming, by Dahl, Dijkstra and Hoare, sits beside this volume on the shelf and was published only four years later. Where Dijkstra emphasised the discipline of constructing programs so they could be reasoned about, Knuth emphasised the analysis of their correctness and cost. The two approaches were allies and occasional rivals. Knuth's 1974 paper on structured programming with go to statements was a careful contribution to that debate, arguing that the goal of clarity sometimes favoured a well-placed jump.
After Knuth, the teaching of algorithms changed. Introduction to Algorithms by Cormen, Leiserson and Rivest, also on this shelf, became the standard university text. It covers far more algorithms than Volume 1 and writes them in pseudocode rather than assembly, and it uses asymptotic analysis rather than exact counts. It is in many ways the accessible successor to Knuth's programme. A reader who knows both will see how much Cormen and his colleagues owe to the framework Knuth established, and how they adapted it for students who need breadth more than depth.
Structure and Interpretation of Computer Programs by Abelson and Sussman takes a different path. It builds understanding of programs through a high-level language, Scheme, and emphasises abstraction rather than machine costs. Reading it beside Knuth is instructive. One book looks down at the machine; the other looks up at ideas. Both are needed. The Lisp-style list structures and garbage collection that appear near the end of Volume 1 are the everyday material of Abelson and Sussman.
On the theoretical side, the shelf holds books on what can be computed and at what cost: Hopcroft and Ullman's Introduction to Automata Theory, Languages, and Computation, Sipser's Introduction to the Theory of Computation, Minsky's Computation: Finite and Infinite Machines, and Garey and Johnson's Computers and Intractability. These work at a higher level of abstraction. Knuth's volume is where their abstractions meet actual instructions on an actual, if imaginary, machine.
Finally, there are the books about building real systems: Brooks's The Mythical Man-Month on managing software projects, Kernighan and Ritchie's The C Programming Language on a language close to the machine, and Hennessy and Patterson's Computer Architecture on how processors are designed. Each of these assumes the kind of foundational knowledge Volume 1 provides. C, in particular, exposes pointers and memory in a way that makes Knuth's linked structures and allocation methods directly applicable.
Questions and criticisms
The most common objection is that the book is too hard. Its mathematics goes well beyond what most programmers use, and its assembly-language programs demand patience. This is a fair point about the book's audience. It is not a fair criticism of the book's aim. Knuth set out to write a complete, exact treatment, and that requires mathematics. A reader who wants an easier entry should begin elsewhere and come to Knuth later, as many do.
A second objection concerns MIX. Critics argue that an imaginary 1960s machine is a strange vehicle for teaching in an age of high-level languages, and that its decimal and binary ambiguity, its six-bit-style bytes and its absence of modern features make it feel antique. Knuth partly accepted this, which is why he designed MMIX. But the deeper point stands: any concrete machine will date, and the analysis it supports does not. Readers who translate the ideas into their own setting lose little.
A third concern is the gap between exact analysis and modern hardware. Knuth's cost model counts instructions, each with a fixed time. Real processors today have caches, pipelines and parallel units, and the time an instruction takes can vary enormously depending on where its data lives. An algorithm with fewer instructions can run slower than one with more if it uses memory badly. Later research on cache-aware and cache-oblivious algorithms grew partly from this gap. Knuth's method remains valid, but the cost model must be updated to fit the machine.
A fourth point is scope. Volume 1 covers fundamentals, and by design it leaves many important topics to later volumes or to no volume yet written. Graph algorithms, for example, are mostly deferred. Readers who expect a complete survey of algorithms in one place will not find it here. The series as a whole remains unfinished more than half a century after it began, and Knuth has said plainly that he may not complete every planned volume.
Almost everything that matters has held up. The definition of an algorithm, the method of assertions, the habit of exact analysis, the core data structures, the vocabulary of trees and lists, the treatment of coroutines and the account of memory allocation all remain standard. Errors in the text have been few and have been corrected with unusual diligence. The book's rigour has made it a reference that later authors cite when they need to be sure of a fact.
What changed most is the surrounding practice. Programmers today rarely implement linked lists or allocators themselves, because libraries do it for them. One might conclude that Knuth's material is now hidden knowledge, needed only by those who write the libraries. But the libraries are built from these ideas, and when a program is slow or a structure behaves strangely, the explanation usually lies here. The knowledge has become less visible, not less necessary.
Why it is on this shelf
This shelf holds books for a reader who moves between Vedanta, Jyotish, science, economics and technology, and who wants in each field the works that go to the root. In computing, this is such a work. It does not describe a product or a trend. It describes what a procedure is, how to tell whether it is right, and how to know what it costs. Those questions do not expire.
There is a kinship here with the older disciplines on the shelf. The Indian traditions of grammar and mathematics prized exact, finite, rule-governed procedures; a careful reader of those traditions will find Knuth's definition of an algorithm familiar in spirit. Jyotish calculation has always been a matter of precise step-by-step computation, and the question of how much effort a computation requires is as old as astronomy. Knuth's insistence on proof and exact counting belongs to the same family of habits as careful commentary on a difficult text.
We also keep it for its manner. It shows what it looks like to treat a subject with complete seriousness: to define terms before using them, to check every claim, to credit predecessors, to grade difficulty honestly, and to keep correcting one's own work for decades. That manner is worth having in view whatever one is working on.
Finally, it is here because it is still being written. Few foundational works are living projects. This one is, and that gives it a particular place among the books on this shelf. It is a reminder that a large and exact undertaking can be carried through a lifetime by steady work.
How to read it
Do not try to read Volume 1 straight through. It is not built for that, and the attempt usually ends somewhere in the mathematical preliminaries. Treat it as a book to live with for several months, reading some parts closely, skimming others, and returning as needed.
Begin with the opening section on algorithms. Read it slowly, work through Euclid's algorithm by hand on a few pairs of numbers, and do the easy exercises. This section sets the tone for everything else and is short enough to master.
Next, skim the mathematical preliminaries rather than working them. Read the opening of each subsection to see what tools are offered, and note which are familiar. Pay particular attention to the short subsection on the analysis of an algorithm, which shows the method in action on a small example. Then move on. Come back to specific preliminaries when a later analysis needs them. Readers who want to master this mathematics properly should work through Concrete Mathematics alongside.
Then read the description of MIX, enough to follow a short program. You do not need to memorise the instruction set. Read the section on subroutines and coroutines with care; these ideas are worth having. Skim the input and output material on a first pass.
Now turn to the second chapter, which is where most readers find the book most rewarding. Read the material on stacks, queues and linked lists closely, and work the algorithms by hand on small examples with pencil and paper, drawing the boxes and arrows. Do the same for tree traversal. This is the part of the book to work through with a pencil.
On a first pass, it is reasonable to skip the more advanced counting results about trees, the multilinked structures section and the detailed analyses of memory allocation, returning to them later. Read the historical notes at the end of each section even when skipping the body; they are short and rewarding.
As for pace, a few pages a day is a good rate for the conceptual sections, and less for the mathematical ones. Choose exercises by rating. Most readers do well to attempt everything rated twenty or less in the sections they read closely, and to read the answers to the others.
For what to read next from this shelf: Introduction to Algorithms by Cormen, Leiserson and Rivest for breadth and a more modern presentation; Structured Programming for the discipline of building correct programs; Structure and Interpretation of Computer Programs for the view from abstraction; Computers and Intractability for what lies beyond efficient algorithms; and Code by Petzold if the machine-level material in MIX felt unfamiliar and you want to see how real hardware works.
Questions to carry
- Which of Knuth's five properties of an algorithm does a modern recommendation system fail to satisfy, and does that matter?
- When would you rather know the average cost of an algorithm than its worst-case cost, and when the reverse?
- What is the cost model behind your own sense that one program is faster than another?
- Is a low-level imaginary machine a better teaching tool than a real high-level language, and for whom?
- Where in your own work do you rely on a stack, a queue or a tree without naming it?
- Why might best-fit allocation lose to first-fit, and what does that say about trusting intuition?
- What invariant must every operation on a doubly linked list preserve?
- How would you explain the difference between a coroutine and a subroutine to someone who has used only one of them?
- What changes in the analysis of an algorithm when memory access times vary by a factor of a hundred?
- Why does Knuth place important results in the exercises rather than the main text?
- What is gained, and what lost, when a library hides a data structure from the programmer who uses it?
- How does the history of an idea change the way you understand it?
- What would it take for a large modern software system to be analysed as exactly as Knuth analyses a single algorithm?
Words to know
- Algorithm: a finite, definite, effective procedure that takes input and produces output, in Knuth's strict sense.
- Computational method: a procedure that has all the properties of an algorithm except that it may not terminate.
- Assertion: a statement about a program's variables that is claimed to hold whenever control reaches a given point.
- Invariant: a condition that remains true throughout a loop or across all operations on a data structure.
- Analysis of algorithms: the study of the exact resources, such as time and memory, that an algorithm uses as a function of its input.
- Asymptotic notation: shorthand such as big-O for describing how a quantity grows, ignoring constant factors and smaller terms.
- Harmonic number: the sum of the reciprocals of the first n whole numbers; it grows like the natural logarithm of n.
- Generating function: a function whose power series coefficients are the terms of a sequence, used to solve counting problems and recurrences.
- MIX: Knuth's imaginary 1960s-style computer, used to present programs and count their costs exactly.
- MMIX: the 64-bit successor to MIX, designed by Knuth to reflect modern processor design.
- Register: a small, fast storage location inside a processor.
- Subroutine: a piece of code that can be called from several places and returns to its caller when done.
- Coroutine: one of two or more routines that pass control back and forth as equals, each resuming where it left off.
- Stack: a list in which items are added and removed only at one end, last in first out.
- Queue: a list in which items are added at one end and removed at the other, first in first out.
- Deque: a double-ended queue allowing insertion and removal at both ends.
- Linked allocation: storing items with pointers to their neighbours rather than in consecutive memory.
- Topological sort: arranging items so that every item comes after all the items it depends on.
- Binary tree: a structure in which each node has at most a left child and a right child, the two being distinguished.
- Traversal: visiting every node of a tree or list in a systematic order.
- Threaded tree: a binary tree whose empty links point to other nodes so it can be traversed without a stack.
- Garbage collection: automatically finding and reclaiming memory that a program can no longer reach.
- Fragmentation: the breaking up of free memory into pieces too small to be useful.
- Buddy system: a memory allocation method using blocks whose sizes are powers of two, merging pairs of free buddies.
A note on this edition
This is a study edition written for this shelf in our own words. It describes and discusses Donald Knuth's The Art of Computer Programming, Volume 1: Fundamental Algorithms, but it does not reproduce the book, its programs, its exercises or its text. The book itself is in copyright and remains in print. It is worth getting from a library or a bookshop and keeping close at hand for a long time.