Computer Fundamentals and Introduction to Programming · Lecture Notes

Chapter 4.1: Algorithms

Whether a program will work is often settled before the first line of code is written. If the problem has been defined precisely, the solution worked out step by step, and a few small examples tried by hand, coding becomes a fairly mechanical translation. This chapter starts with defining a problem, then covers the properties of a good algorithm, the algorithm design cycle, and pseudocode. Five small algorithms are then traced line by line: ordering two numbers, factorial, the Fibonacci sequence, palindrome checking, and primality testing. We check an algorithm's correctness with a trace table and test cases, and measure its efficiency by counting operations. The last two sections turn to two of the most basic tasks in computer science: linear and binary search, and selection, bubble, insertion, and merge sort. Each method is run step by step on an example array, and every comparison it makes is counted.

Learning outcomes

Defining
Identify a problem's goal, input, output, constraints, check example, and error case.
Designing
Break a solution into clear, ordered, executable, finite steps, and write the algorithm in pseudocode.
Verifying
Run an algorithm by hand with a trace table, and choose test cases made up of normal, boundary, invalid, and large inputs.
Comparing
Evaluate linear and binary search, and selection, bubble, insertion, and merge sort, in terms of number of comparisons, time complexity, and space complexity.

4.1.1Problem solving

A beginner who reads an assignment usually wants to sit down at the computer and start typing code right away. For short assignments this sometimes works. Once the problem grows a little, the code swells with trial and error, fixing one bug introduces another, and it becomes unclear why the program works or why it does not. Experienced programmers do the opposite: they first understand the problem, then work out the solution on paper, and write the code last. Problem solving is the name of this disciplined approach.

4.1.1.1Algorithm first, code second

Code is the expression of a solution idea in a particular programming language. The same idea can be written in Java, in Python, or in C; only the syntax changes. The idea itself, the sequence of steps that solves the problem, is independent of the language. This sequence of steps is called an algorithm. Code written before the algorithm is clear causes two troubles. First, the programmer decides what to do while typing and so makes needless experiments. Second, some cases are never considered, which leaves hidden bugs: the program works on the sample input and gives a wrong result on another.

Understand the problemlargest number?Solve an example3, 8, 5 → 8Write the methodlargest = firstupdate when you see a larger oneCode itJava, Python, C…The orange step (the algorithm) is independent of the language; the same method can be coded in any language.
Figure 4.1.1: The right order for solving a problem: understand the problem, solve a small example by hand, write the method, then code it. The example problem is finding the largest number in a list. The orange step (the algorithm) is independent of the language; the same method can be coded in any language.

Figure 4.1.1 shows this order on the problem “find the largest number.” The first step is understanding the problem: can the list be empty, can the numbers be negative, can the same number occur more than once? In the second step, a small example is solved by hand. In the list 3, 8, 5 the largest number is 8. Without noticing, a person follows a method while finding it: look at the numbers from left to right and remember the largest value seen so far. In the third step this method is written down explicitly: “The largest value starts as the first element of the list; if the next element is larger, update the largest value.” The fourth step is coding; the method is now settled, and all that remains is to apply the syntax rules of the chosen language.

The second step is often skipped, yet it is the most instructive. The example solved by hand gives a draft of the algorithm. Every operation performed while solving the example becomes a step of the algorithm, and every piece of information kept in mind becomes a variable. In the largest-number example the information kept in mind is “the largest value so far”; in the program this becomes a variable called largest.

4.1.1.2Problem definition

To understand a problem is to write it down in a way that answers a few questions. Together, the answers to these questions form the problem definition.

Definition 4.1.1

A problem definition states six elements of the problem to be solved: the goal (which problem is to be solved), the input (what information is given to the program), the output (what result is produced), the constraint (the limits and validity conditions of the values), the example (which small case will verify the expected result), and the error case (what to do on invalid or missing input).

Each of these six elements settles in advance a decision that would otherwise have to be made while writing code. The goal determines when the program counts as “finished.” The input and output say how the program talks to the outside world. The constraint limits the values for which the program must work correctly. The example prepares the first check to run once the program is written. The error case is the element most often forgotten: it is what makes the program give a meaningful message, instead of crashing, when the user enters an unexpected value.

Input: nintegerAlgorithmcompute factorialOutput: n!5 → 120Constraint: 0 ≤ n ≤ 20 (fits in a long) · error if n < 0
Figure 4.1.2: Summary of the problem definition for computing a factorial. The input is an integer n, the output is n!; the constraint is 0 ≤ n ≤ 20 (the result fits in the 64-bit long type), and an error is reported if n < 0.
Example 4.1.1

How is a complete problem definition written for the request “compute the factorial of a number”?

The factorial is the product of the integers from 1 to n: 5! = 1 × 2 × 3 × 4 × 5 = 120. By definition, 0! = 1. The six elements of the problem definition are filled in as follows:

ElementAnswer for the factorial problem
GoalCompute the factorial of the given number n
InputAn integer n
OutputThe value of n!
Constraint0 ≤ n ≤ 20 (the result will be held in the 64-bit long type)
Example120 for n = 5; 1 for n = 0
Error caseIf n < 0 or n > 20, print “error”

The limit of 20 in the constraint row is not arbitrary. Java's long type holds at most 9,223,372,036,854,775,807. 20! = 2,432,902,008,176,640,000 stays below this limit, while 21! = 51,090,942,171,709,440,000 goes above it.

Common mistake

Writing only the input and output in the problem definition and skipping the constraint and the error case. The sentence “compute the factorial of n” does not say what happens when n = −3 is entered. If this question is not answered at design time, the program either gives a meaningless result or enters a loop that never stops. The constraint and the error case are at least as important as the input and output.

4.1.2Algorithm

4.1.2.1What is an algorithm?

Everyday life is full of algorithms. A recipe, the assembly instructions of a piece of furniture, and the steps for withdrawing money from an ATM can all be called algorithms. In each of them there are steps to be carried out in order to reach a particular result. In computer science the notion of an algorithm is defined more precisely, because the one carrying out the steps is not a person but a machine that cannot interpret anything on its own.

Definition 4.1.2

An algorithm is a finite sequence of well-defined steps for solving a particular problem. An algorithm takes zero or more inputs and produces at least one output.

The phrase “zero or more inputs” in the definition may look odd at first. Some algorithms take no input at all: the task “print the numbers from 1 to 100” asks for no information from outside. An algorithm with no output, on the other hand, is useless; a computation whose result is reflected nowhere is no different from a computation that was never done. The output may be a number printed on the screen, but it may equally be data saved to a file or a signal that starts a motor.

4.1.2.2Properties of a good algorithm

Not every sequence of steps is a good algorithm. The sentence “arrange the numbers appropriately” looks like a step, but the word “appropriately” does not say what to do. For an algorithm to run reliably on a computer, its steps must have certain properties.

Table 4.1.1: Properties of a good algorithm.
PropertyMeaningWhat happens when it fails
DefinitenessEvery step is clear and has a single meaningDifferent people carry out a step like “enlarge it a bit” differently
OrderingThe order in which steps are performed is fixedIf the order of assignments in a swap changes, a value is lost
FeasibilityEvery step can actually be carried outThe step “list all prime numbers” can never be completed
FinitenessThe algorithm stops after a finite number of stepsThe loop condition never becomes false, so the program never stops
CorrectnessProduces the right result for every valid inputThe program gives a wrong result on some inputs
EfficiencyResource use stays acceptable as the input growsA program that is fast on small data runs for hours on large data

Table 4.1.1 lists six properties and the symptom seen when each one fails. Of these, definiteness and finiteness are the most often overlooked. A small example shows how subtle the condition for finiteness can be.

i = 1; while i ≠ 10: i = i + 2never hits 10: does not stop ✗01234567891011121314…i = 1; while i ≤ 10: i = i + 2stops when i = 11 ✓01234567891011121314
Figure 4.1.3: Finiteness. In the upper loop, i starts at 1 and grows by two: 1, 3, 5, … The value is never exactly 10, so the condition i ≠ 10 stays true and the loop never stops. In the lower loop the condition is i ≤ 10; when i = 11 the condition becomes false and the loop stops.

Figure 4.1.3 compares two loops. In both, the counter starts at 1 and increases by 2 on every iteration. The upper loop says “keep going as long as i is not equal to 10.” The counter runs 1, 3, 5, 7, 9, 11, 13 … and skips over 10. Since the condition never becomes false, the loop goes on forever. The lower loop says “keep going as long as i is less than or equal to 10.” When the counter reaches 11, 11 ≤ 10 is false and the loop ends. The difference between the two conditions is a single symbol, but one of them is an algorithm and the other is not.

Common mistake

Using an equality condition (= or ≠) to end a loop. If the counter never lands exactly on that value, the loop never stops. When a counter moves toward a limit, a “less than or equal” (≤) or “less than” (<) condition is safer; the moment the counter passes the limit, the loop is guaranteed to end.

Correctness and efficiency are separate properties. A correct algorithm can be slow, and a fast algorithm can give a wrong result on some inputs. Correctness comes first; a fast but wrong result has no value. Efficiency gains importance as the input grows.

4.1.2.3The algorithm design cycle

A good algorithm rarely appears on the first attempt. Design is a cycle repeated several times. On each pass the algorithm becomes a little clearer and overlooked cases are caught.

1. Solve an example2. Find the general rule3. Write pseudocode4. Trace by hand5. Fix
Figure 4.1.4: The algorithm design cycle: solve an example, find the general rule, write pseudocode, trace by hand, fix. If the hand trace reveals an error, it is corrected and the cycle runs again; when no errors remain, we move on to coding.

The five steps in Figure 4.1.4 work as follows:

  1. Solve an example. A small instance of the problem is solved by hand. For the factorial, we compute 4! = 1 × 2 × 3 × 4 = 24.
  2. Find the general rule. We notice the repetition in the hand computation: at every step, the product so far is multiplied by the next number. The rule is written as “start the product at 1 and multiply it by every number from 2 to n.”
  3. Write pseudocode. The rule is turned into clear steps that are close to a programming language but not tied to one.
  4. Trace by hand. The pseudocode is run line by line on a few inputs, like a computer would, and the value of each variable is written in a table.
  5. Fix. If the trace shows a difference between the expected and the actual result, the error is located and the pseudocode is corrected. The cycle then runs again: the corrected pseudocode is traced once more.

The cycle ends when the hand trace no longer reveals errors, and coding begins. If several solutions have been found for the same problem, they are compared at this stage for correctness, readability, and efficiency. Readability should not be underestimated: the person who reads an algorithm most is the programmer who has to modify it a few months later.

4.1.2.4Pseudocode

There are several ways to write down an algorithm. Steps written in everyday language are easy to understand but open to ambiguity. Steps written in a programming language are precise but full of syntax rules; semicolons and parentheses get in the way of thinking. Pseudocode sits between these two extremes.

Definition 4.1.3

Pseudocode is a way of writing the logic of an algorithm in short, consistent statements close to natural language, without tying it to any particular programming language.

Pseudocode has no single universally accepted syntax. What matters is that within one algorithm the same statement always has the same meaning. The statements used in this chapter are: read takes an input, print produces an output, = assigns the value on the right to the variable on the left, if … then checks a condition, while … repeats the lines below it as long as the condition is true, and for … to … repeats a fixed number of times. Indentation, the whitespace at the start of a line, shows which lines a condition or loop covers.

The simplest example is an algorithm that prints the sum of two numbers:

START
  read A
  read B
  SUM = A + B
  print SUM
END

The same algorithm can also be drawn as a flowchart. Figure 4.1.5 shows the counterpart of each pseudocode line in the diagram: start and end are ovals, input and output are parallelograms, and a computation is a rectangle. Arrows show the order of the steps.

STARTread Aread BSUM = A + Bprint SUMEND
Figure 4.1.5: Flowchart of the addition algorithm: start, read A, read B, SUM = A + B, print SUM, end.

The goal of pseudocode is not to follow syntax rules but to make the algorithm understandable. That is why a line such as “swap arr[i] and arr[j]” can be written freely in pseudocode. In Java the same job takes three assignments, but from the point of view of the algorithm's logic it is a single step. Once the pseudocode is ready, translating it into code is often a line-by-line task: an if … then line becomes if, and a while … line becomes while.

Common mistake

Writing pseudocode that is either too vague or too detailed. The line “process the list and find the result” says nothing. At the other extreme, pseudocode that puts a semicolon at the end of every line and declares every variable type is really Java code and loses the convenience of pseudocode. The yardstick is this: someone reading the pseudocode should be able to write the algorithm in whatever language they know.

4.1.3Example algorithms

The best way to learn to build algorithms is to solve small, well-known problems. The five examples in this section get progressively harder. The first contains only one condition and three assignments. The factorial and Fibonacci examples bring in loops and the idea of accumulation. In the palindrome and prime examples, the loop ends early as soon as the result is known. In each example the pseudocode is given first, and then the algorithm is traced step by step on one input.

4.1.3.1Ordering two numbers and swapping

The problem: read two numbers and print the smaller one first. If a = 7, b = 3 is entered, the output must be “3 7”; for a = 2, b = 9, it is “2 9”. The idea is simple. If a is greater than b, the values of the two variables are exchanged; otherwise they are already in the right order. Exchanging the values of two variables is called a swap.

read a, b
if a > b then
    temp = a
    a = b
    b = temp
print a, b

Line 2 of the algorithm checks the condition. If it is true, the three indented lines run; if it is false, they are skipped. When the values are equal (a = b), the condition is false and no swap happens, which is fine because none is needed. The last line runs in both cases and prints output satisfying a ≤ b.

Why a swap needs three assignments is the most instructive part of the algorithm. A variable can hold only one value at a time. The moment a new value is written into a with a = b, its old value is erased. If the old value has not been copied somewhere beforehand, it can never be recovered. That is why the value of a is first copied into a temporary variable.

a7 → 3temp— → 7b3 → 7① temp = a③ b = temp② a = b
Figure 4.1.6: The three assignments of a swap. ① temp stores a's value 7. ② a takes the value 3 from b; a's old value now lives only in temp. ③ b takes the value 7 from temp.

Figure 4.1.6 shows the three assignments with arrows. The assignments form a cycle: from a to temp, from b to a, from temp to b. The step-by-step run of the algorithm for a = 7, b = 3 is given in Table 4.1.2.

Table 4.1.2: Trace table of the two-number ordering algorithm for a = 7, b = 3. Each row shows the values after that line has run; “—” means the variable has not yet received a value.
StepLine executedabtemp
1read a, b73—
2if 7 > 3 then73—
3temp = a737
4a = b337
5b = temp377
6print a, b → 3 7377

In row 4 of the table, a and b are both 3. This is the most fragile moment of the algorithm: the value 7 lives only in temp. In row 5 the 7 in temp is copied to b and the swap is complete. Had a = 2, b = 9 been entered, the condition 2 > 9 in row 2 would be false, rows 3–5 would never run, and “2 9” would be printed directly.

a7b3temp7copy a3b3temp7copy a3b7temp7copy
Figure 4.1.7: The three moments of the swap (in order): after temp = a (a = 7, b = 3, temp = 7); after a = b (a = 3, b = 3, temp = 7); after b = temp (a = 3, b = 7, temp = 7).
Common mistake

Writing the swap without a temporary variable, with two assignments a = b and b = a. For a = 7, b = 3, the first assignment makes a equal to 3 and erases the 7. The second assignment writes a's new value, 3, into b. The result is “3 3”; the 7 is lost. Assignment is a copying operation; it does not exchange the contents of two boxes at the same time.

The idea of ordering two numbers can be extended to more numbers. For three numbers, the two-number ordering step is applied three times: first a with b, then b with c, and finally a with b again.

Example 4.1.2

How does the algorithm below work for a = 8, b = 5, c = 1? Why are three comparisons enough?

read a, b, c
if a > b then swap a and b
if b > c then swap b and c
if a > b then swap a and b
print a, b, c
StepConditionResultabc
start——851
1st comparisona > btrue → a and b are swapped581
2nd comparisonb > ctrue → b and c are swapped518
3rd comparisona > btrue → a and b are swapped158

The output is “1 5 8”. Because the input was in reverse order, all three comparisons caused a swap. The first two comparisons carry the largest value to the far right, like a bubble: after step 1 the 8 moves to b, and after step 2 to c. Now c definitely holds the largest value. What remains is to order a and b, which the 3rd comparison does. That is why three comparisons are always enough for three numbers.

4.1.3.2Factorial

The factorial of n is the product of the integers from 1 to n, written n!. 3! = 1 × 2 × 3 = 6 and 5! = 120. By definition, 0! is 1. The problem definition of the factorial was written in 4.1.1.2; the algorithm follows that definition step by step.

read n
if n < 0 then print "error" and stop
result = 1
i = 2
while i ≤ n
    result = result × i
    i = i + 1
print result

The lines do the following:

  1. read n: the number whose factorial is to be computed is read.
  2. if n < 0 then print "error" and stop: the factorial of a negative number is not defined. This line handles the error case in the problem definition.
  3. result = 1: the starting value of the product is 1. The variable builds up the product step by step.
  4. i = 2: the counter starts at 2. Multiplying by 1 does not change the value, so there is no need to start at 1.
  5. while i ≤ n: as long as i does not exceed n, the two lines below it are repeated.
  6. result = result × i: the product so far is multiplied by i.
  7. i = i + 1: the counter increases by one; then control returns to line 5 and the condition is checked again.
  8. print result: when the loop ends, the result is printed.

A variable like the one in line 3, which builds up a result step by step over a loop, is called an accumulator. The accumulator's starting value is chosen according to the operation. For addition we choose 0, because adding 0 does not change the sum. For multiplication we choose 1, because multiplying by 1 does not change the product.

n = 5: at the start of each iteration result = (i − 1)!1i = 2× 22i = 3× 36i = 4× 424i = 5× 5120i = 6 → stop
Figure 4.1.8: The factorial chain for n = 5. At the start of each iteration result = (i − 1)!: 1 at i = 2, 2 at i = 3, 6 at i = 4, 24 at i = 5. In the last iteration 24 × 5 = 120 is obtained; the loop stops when i = 6.

Figure 4.1.8 shows how the product grows. The full trace of the algorithm for n = 5 is given in Table 4.1.3.

Table 4.1.3: Trace table of the factorial algorithm for n = 5. The “Condition” column is the condition i ≤ n checked at the start of the iteration.
StateCondition i ≤ nMultiplyresultNew i
start——12
Iteration 12 ≤ 5 → true1 × 2 = 223
Iteration 23 ≤ 5 → true2 × 3 = 664
Iteration 34 ≤ 5 → true6 × 4 = 24245
Iteration 45 ≤ 5 → true24 × 5 = 1201206
exit6 ≤ 5 → false—1206

The table shows that the loop runs 4 times: i takes the values 2, 3, 4, and 5. In general, for n ≥ 2 the loop runs n − 1 times. When i = 6, the condition 6 ≤ 5 is false and the loop ends; 120 is printed.

A pattern stands out in the result column of the table. At the start of every iteration, result equals the factorial of one less than i: 1 = 1! when i = 2, 2 = 2! when i = 3, 6 = 3! when i = 4. A statement like this, which stays true on every iteration of the loop, is called a loop invariant.

Definition 4.1.4

A loop invariant is a statement that is true at the start of every iteration of a loop. The loop invariant of the factorial algorithm is “at the start of each iteration, result = (i − 1)!.”

The loop invariant shows why the algorithm is correct. When the loop starts for the first time, i = 2 and result = 1 = 1!; the statement holds. In one iteration, result is multiplied by i and i increases by one. If result = (i − 1)! before the iteration, then after it result = (i − 1)! × i = i!. Since the new i is one more than the old i, the statement holds again. The loop ends when i = n + 1; at that moment result = n!, which is exactly the desired result.

The invariant also explains how the algorithm behaves on small inputs. For n = 0 or n = 1, the condition 2 ≤ n is false at the first check. The loop never runs and result stays 1; 0! and 1! are 1 anyway. The algorithm needs no separate line for these two cases.

Common mistake

Giving the accumulator the wrong starting value, or writing the loop bound one short. If result = 0 is written, every product comes out 0 and the algorithm prints 0 for every n. If the condition is written i < n instead of i ≤ n, the last multiplication is skipped; for n = 5 the result is 24 instead of 120. The second mistake is called an off-by-one error. An off-by-one error does not show up for the inputs n = 0 and n = 1, because the loop does not run there anyway. That is why an algorithm should never be tried on a single input and then left.

The accumulator idea is used not only for the factorial but in every problem that needs a sum, a count, or an average. The following example applies the same pattern to addition.

Example 4.1.3

How is an algorithm written that finds the sum of the even numbers from 1 to n? How does it work for n = 10?

Since we are adding, the accumulator starts at 0. Even numbers start at 2 and grow by two; the counter likewise starts at 2 and is increased by 2 on every iteration. This way the odd numbers are never looked at.

read n
sum = 0
i = 2
while i ≤ n
    sum = sum + i
    i = i + 2
print sum
StateCondition i ≤ nsumNew i
start—02
Iteration 12 ≤ 10 → true24
Iteration 24 ≤ 10 → true66
Iteration 36 ≤ 10 → true128
Iteration 48 ≤ 10 → true2010
Iteration 510 ≤ 10 → true3012
exit12 ≤ 10 → false3012

The result is 2 + 4 + 6 + 8 + 10 = 30. The loop runs 5 times; when the counter reaches 12 the condition becomes false. For n = 0 or n = 1 the condition is false at the first check and 0 is printed; this is correct, since there is no positive even number less than or equal to 1. It matters that the loop condition uses ≤: for n = 10, 10 itself must be included in the sum.

4.1.3.3The Fibonacci sequence

The Fibonacci sequence starts with 0 and 1; every following term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, … The problem is to print the first n terms of the sequence. In the factorial it was enough to remember a single value on each iteration. Here, computing the new term requires keeping the two previous values together.

read n
a = 0, b = 1
for round = 0 to n-1
    print a
    next = a + b
    a = b
    b = next

a and b hold two consecutive terms of the sequence. On each iteration a is printed, then a and b are added to find the next term. Then the two variables advance by one term: a takes the value of b, and b takes the value of the new term. Together, a and b are like a two-cell window that slides one position to the right along the sequence on each iteration. This technique is called a sliding window.

011235813abnext2 + 3 = 5Round 3: a (2) is printed, next = a + b; then a = 3, b = 5 and the window slides one to the right.
Figure 4.1.9: The sliding window on the Fibonacci sequence. In round 3, a = 2 is printed and next = a + b = 2 + 3 = 5 is computed; then a = 3, b = 5 and the window slides one to the right.

Figure 4.1.9 shows the state in the third round. All rounds of the algorithm for n = 8 are traced in Table 4.1.4.

Table 4.1.4: Trace table of the Fibonacci algorithm for n = 8. Rounds are numbered from 0 to n − 1 = 7; “New a” and “New b” are the values at the end of the round.
Rounda printednext = a + bNew aNew b
start——01
000 + 1 = 111
111 + 1 = 212
211 + 2 = 323
322 + 3 = 535
433 + 5 = 858
555 + 8 = 13813
688 + 13 = 211321
71313 + 21 = 342134

The output is the sequence in the “a printed” column: 0 1 1 2 3 5 8 13. In the last round next = 34 is computed but never printed; the loop ends after 8 rounds. This small waste is the price paid for the simplicity of the algorithm. For n = 0 the algorithm prints nothing, and for n = 1 it prints only 0; both are the expected results.

output:011a1b2next3 output:011a2b2next3 output:011a2b3next3
Figure 4.1.10: Fibonacci, the last three steps of round 2 (in order): next = 1 + 2 = 3 is computed; with a = b, a becomes 2; with b = next, b becomes 3. The top row shows the terms printed so far.

The order of the last two assignments raises a problem similar to the one in the swap. As in Figure 4.1.10, first a = b is executed, then b = next. If the order is reversed, the assignment b = next erases the old value of b. Then a = b writes the new term into a, not the old b. a and b become equal, and on every round the new term is computed as a + a = 2a. The sequence then doubles each time: 0, 1, 2, 4, 8.

Common mistake

Ignoring the order of interdependent assignments. Before a new value is written to a variable, every operation that needs its old value must be finished. In Fibonacci, the old b is needed for a; that is why a = b is written first. The temporary variable (here next) preserves this order by storing the new value the moment it is computed.

4.1.3.4Palindromes

A word or sentence that reads the same backward as forward is called a palindrome. “kayak,” “ses,” and “kazak” are palindromes (they are Turkish words, for boat, voice, and sweater); “kayık” is not. The problem is to report, as true or false, whether a given text is a palindrome.

The first solution that comes to mind is to reverse the text and compare it with itself. This is correct, but it creates a copy of the text. A solution that does less work starts at the two ends of the text and moves toward the middle. The first letter is compared with the last, the second with the second from last. If a differing pair is found, the text is not a palindrome and false is returned at once. If no differing pair appears before the ends meet in the middle, the text is a palindrome.

read text
clean text by the rule
lo = 0, hi = length - 1
while lo < hi
    if the characters differ, return false
    lo = lo + 1, hi = hi - 1
return true

The step “clean text by the rule” in the second line is part of the problem definition. In the word “Kayak” the first letter is a capital K; if letters are compared as they are, K ≠ k is assumed and the right answer is missed. That is why a rule is fixed before the algorithm runs. The rule in the example is: convert all letters to lowercase and discard spaces and punctuation. “Kayak” thus becomes “kayak.”

0k1a2y3a4klo = 0 →← hi = 4Outside in: k = k, a = a; no comparison needed for the middle y → ⌊5 / 2⌋ = 2 comparisons
Figure 4.1.11: Comparison from both ends toward the center in the word “kayak”: k with k, a with a. The middle y is not compared with itself; for 5 letters, ⌊5 / 2⌋ = 2 comparisons are enough.

Figure 4.1.11 shows the compared pairs with arcs. lo and hi are the indices of the two letters being compared, that is, their positions in the text. Indices start at 0: in the word “kayak,” text[0] = 'k' and text[4] = 'k'. The trace of the algorithm is in Table 4.1.5.

Table 4.1.5: Trace table of the palindrome algorithm for “Kayak.” The cleaned text is “kayak,” length 5; initially lo = 0, hi = 4.
Comparinglohilo < hitext[lo]text[hi]Decision
1040 < 4 → true'k''k'same, move inward
2131 < 3 → true'a''a'same, move inward
—222 < 2 → false——loop ends → return true

At the third check, lo and hi are both 2; we have reached the middle letter. Since 2 < 2 is false, the loop ends and true is returned. For a text of length n the loop runs at most ⌊n / 2⌋ times. The ⌊ ⌋ symbol means the number is rounded down: ⌊5 / 2⌋ = ⌊2.5⌋ = 2. In a text of even length, for example the word “abba,” lo and hi cross in the middle: after 2 comparisons lo = 2, hi = 1 and the loop ends again.

The algorithm stops even earlier on texts that are not palindromes. For “Kayık,” the first comparison finds k and k the same. In the second comparison a and ı differ, and false is returned; the middle y is never looked at.

Example 4.1.4

Is the sentence “Ey Edip Adana'da pide ye” (Turkish for “Hey Edip, eat pide in Adana”) a palindrome? How many comparisons are made?

First the cleaning rule is applied: letters are lowercased, and spaces and the apostrophe are discarded. The result is the 19-letter text “eyedipadanadapideye.” Initially lo = 0, hi = 18.

Comparinglohilo < hitext[lo]text[hi]Decision
10180 < 18 → true'e''e'same, move inward
21171 < 17 → true'y''y'same, move inward
32162 < 16 → true'e''e'same, move inward
43153 < 15 → true'd''d'same, move inward
54144 < 14 → true'i''i'same, move inward
65135 < 13 → true'p''p'same, move inward
76126 < 12 → true'a''a'same, move inward
87117 < 11 → true'd''d'same, move inward
98108 < 10 → true'a''a'same, move inward
—999 < 9 → false——loop ends → return true

In all nine comparisons the letters match; lo and hi meet at the middle letter, the 'n' at index 9. The sentence is a palindrome, and ⌊19 / 2⌋ = 9 comparisons were made. Without cleaning, the first comparison would treat capital 'E' and lowercase 'e' as different, and the answer would come out wrong.

Common mistake

Forgetting the letters I and İ when lowercasing Turkish text. In many programming languages, lowercasing applies the English rule unless a locale is specified, and turns “I” into “i.” In Turkish, however, the lowercase of “I” is “ı” and the lowercase of “İ” is “i.” The word “Irmak” becomes “irmak” under the English rule, and palindrome, search, or sorting results come out wrong. When the cleaning rule is written, the language of the text must be taken into account.

4.1.3.5Prime numbers

A number greater than 1 that has no positive divisor other than 1 and itself is called a prime number. 2, 3, 5, 7, 11, and 13 are prime; 9 = 3 × 3 and 21 = 3 × 7 are not. The problem is to report whether a given number n is prime.

The definition directly yields an algorithm: try dividing n by every number from 2 to n − 1. If a number that divides it with no remainder is found, n is not prime. The remainder is computed with the % operation. 29 % 5 = 4, because 29 = 5 × 5 + 4. If n % i = 0, then i divides n exactly. This method is correct but does more work than necessary. The algorithm given here answers the same question with far fewer trials.

read n
if n < 2 then print "not prime" and stop
i = 2
while i × i ≤ n
    if n % i == 0 then print "not prime" and stop
    i = i + 1
print "prime"

The algorithm has two important properties. First, the search stops as soon as a divisor is found; there is no need to look at the remaining candidates. Second, the loop runs as long as the condition i × i ≤ n holds, that is, as long as i does not exceed √n. The reason for this square-root bound is the following: if n splits into two factors a × b, then a and b cannot both be greater than √n. If both were larger, their product would exceed n. So if n has a divisor greater than 1, it also has one that is less than or equal to √n.

12346 = √36912183636 = 1×36 = 2×18 = 3×12 = 4×9 = 6×6: the smaller of each pair is ≤ √36 → trying i = 2…6 is enough
Figure 4.1.12: The divisor pairs of 36: 1 × 36, 2 × 18, 3 × 12, 4 × 9, 6 × 6. The smaller member of each pair is less than or equal to √36 = 6; so trying the range i = 2, …, 6 is enough.

Figure 4.1.12 shows this observation for 36. Each arc connects a divisor pair. The left ends of the arcs are always in the green region, that is, to the left of 6 or at it. Writing the condition as i × i ≤ n instead of using the square root is a deliberate choice: integer multiplication replaces a fractional square-root computation, and there is no rounding error.

Table 4.1.6: Trace table of the prime algorithm for n = 29. Each row is one loop check.
ii × i ≤ nn % iDecision
24 ≤ 29 → true29 % 2 = 1not a divisor
39 ≤ 29 → true29 % 3 = 2not a divisor
416 ≤ 29 → true29 % 4 = 1not a divisor
525 ≤ 29 → true29 % 5 = 4not a divisor
636 > 29 → false—loop ends → prime
n = 29i:229%2=1329%3=2429%4=1529%5=467√29 ≈ 5.392, 3, 4, 5 tried; 6 and beyond unnecessary
Figure 4.1.13: The divisors tried for n = 29. The dashed line is the bound √29 ≈ 5.39: only 2, 3, 4, and 5 are tried; 6 and beyond are unnecessary.

Table 4.1.6 and Figure 4.1.13 show the same run in two forms. 29 is divisible by none of the four candidates. When i = 6, 36 ≤ 29 is false and the loop ends. Since no divisor was found, “prime” is printed. The method taken from the definition would try 27 candidates, from 2 to 28; the square-root bound reduces this to 4. Had n been 21, 21 % 3 = 0 would be found at i = 3, “not prime” would be printed, and the algorithm would end after two trials.

Example 4.1.5

Is 221 prime? How many % operations does the algorithm perform?

221 is odd, it is not divisible by 3 because its digits sum to 5, and it does not end in 5. At first glance it may look prime. Since √221 ≈ 14.87, the algorithm tries at most up to i = 14.

ii × i ≤ nn % iDecision
24 ≤ 221 → true221 % 2 = 1not a divisor
39 ≤ 221 → true221 % 3 = 2not a divisor
416 ≤ 221 → true221 % 4 = 1not a divisor
525 ≤ 221 → true221 % 5 = 1not a divisor
636 ≤ 221 → true221 % 6 = 5not a divisor
749 ≤ 221 → true221 % 7 = 4not a divisor
864 ≤ 221 → true221 % 8 = 5not a divisor
981 ≤ 221 → true221 % 9 = 5not a divisor
10100 ≤ 221 → true221 % 10 = 1not a divisor
11121 ≤ 221 → true221 % 11 = 1not a divisor
12144 ≤ 221 → true221 % 12 = 5not a divisor
13169 ≤ 221 → true221 % 13 = 0divisor found → not prime

At i = 13 the remainder is 0: 221 = 13 × 17. The algorithm prints “not prime” and stops. 12 candidates, from 2 to 13, have been tried, and the % operation has been performed 12 times. The smaller factor, 13, is below the √221 bound and so is caught; the larger one, 17, is never reached.

Common mistake

Writing the square-root bound as i × i < n, leaving out equality. This error shows up on perfect squares. For n = 49, when i = 7, 49 < 49 is false; the loop ends without trying 7. Since no number from 2 to 6 divides 49, the algorithm wrongly says 49 is “prime.” Perfect squares such as 4, 9, 25, and 49 are good test inputs for this bound.

4.1.4Verifying an algorithm

That an algorithm has been written does not show that it works. Correctness is tested in two ways. The first is to run the algorithm on small inputs line by line, as a computer would. The second is to try the algorithm's behavior on different kinds of inputs. The two methods complement each other.

4.1.4.1Hand tracing and the trace table

Running an algorithm on paper, applying each line in order, is called hand tracing. During a trace, the values of the variables are not kept in the head but written in a table. Rows show time, columns show variables. Such a table is called a trace table. All the tables in the previous section are trace tables.

Definition 4.1.5

A trace table is a table in which the value of each variable at each step is recorded while an algorithm is run by hand. Each column corresponds to a variable or a condition being checked, and each row to a step or a loop iteration.

The most important decision when preparing a trace table is what a row represents. Is the variable's value at the start of the iteration written, or its value at the end? If the two are mixed, the table becomes misleading. That is why this decision is stated explicitly in the table's caption or below it.

Example 4.1.6

How is the factorial algorithm traced for n = 4? In the table, the i column shows the value at the start of the iteration and the result column the value at the end.

Stateiresulti ≤ n
start21—
iteration 122true
iteration 236true
iteration 3424true
exit5245 ≤ 4 false

The loop runs 3 times and 24 is printed; since 4! = 24, the result is correct. The loop invariant can also be checked on every row of the table: at the start of iteration 1, with i = 2, result is 1 = 1!; at the start of iteration 2, with i = 3, result is 2 = 2!.

The trace table is used not only to show correctness but also to find errors. When an algorithm gives a wrong result, the expected and actual values are compared row by row. The first row where the two values diverge shows where the error is. For example, if the condition of the factorial algorithm was mistakenly written i < n, then for n = 4 the table proceeds correctly up to iteration 2. When i = 4 the condition comes out false and iteration 3 is never performed. The location of the error is the loop condition.

Common mistake

Applying, during the trace, what the algorithm is supposed to do rather than what it says. Because the person tracing knows the goal of the algorithm, they unknowingly “correct” an overlooked line and fail to see the error. Hand tracing works when the lines are applied mechanically, exactly as written.

4.1.4.2Test cases

A trace table shows that an algorithm works for one input. A single successful trial, however, does not prove that the algorithm is correct for every input. The off-by-one error in the factorial algorithm is invisible when tried with n = 1; the algorithm gives the correct answer, 1. That is why an algorithm is tested with a few carefully chosen inputs. A pair consisting of an input and the output expected for it is called a test case.

Definition 4.1.6

A test case is a pair consisting of an input to be given to an algorithm and the output expected for that input. Test cases fall into four kinds: normal (common use), boundary (values at the edge of the constraint), invalid (values outside the constraint), and large (values that expose scale problems such as overflow or slowness).

The expected output of a test case is written before the algorithm is run. Running the algorithm first and writing its result into the “expected” column makes the test meaningless. The expected value must come from the problem definition and from a hand computation.

-3052021-3 → "error"0 → 15 → 12020! fits21! overflowsinvalid (n < 0)valid: 0 ≤ n ≤ 20long overflows
Figure 4.1.14: The number line for the factorial input. Negative values are invalid (−3 → “error”); 0 is the lower bound (0! = 1); 5 is a normal input (120); 0 to 20 is valid; from 21 on, the result does not fit in the long type.

Figure 4.1.14 shows the regions of the factorial input. At least one test is chosen from each region; the boundaries between regions are tried separately, because errors tend to hide at boundaries. Table 4.1.7 gives such a set of tests.

Table 4.1.7: Test cases for the factorial algorithm (constraint 0 ≤ n ≤ 20). The expected values were computed with Python's unbounded integers.
KindGoalInputExpected
NormalVerify common usen = 5120 (the loop runs 4 times)
BoundaryTry the lower boundn = 01 (the loop never runs)
BoundaryA second case where the loop never runsn = 11 (the loop never runs)
BoundaryTry the upper boundn = 202,432,902,008,176,640,000 (the loop runs 19 times)
InvalidSee the error behaviorn = −3“error”
LargeSee the overflown = 2151,090,942,171,709,440,000 → does not fit in long; the constraint check must give “error”

The last row of the table shows a special case. The value of 21! is itself correct, but Java's 64-bit long type can hold at most 9,223,372,036,854,775,807. 21! exceeds this limit by about a factor of 5.5. On a computation that exceeds the limit, Java does not report an error; the result silently wraps around. When the algorithm is run in Java with long, 21! gives a negative, meaningless number such as −4,249,290,049,419,214,848. A value exceeding the limit of the data type that holds it is called overflow.

This test reveals a gap in the algorithm: the upper bound of the constraint is never checked. The constraint “0 ≤ n ≤ 20” written in the problem definition must also be reflected in the algorithm. The corrected algorithm checks both bounds together before it starts processing the input:

read n
if n < 0 or n > 20 then print "error" and stop
result = 1
i = 2
while i ≤ n
    result = result × i
    i = i + 1
print result

In this version, when n = 21 is entered the loop is never entered and “error” is printed. As we see, testing does not merely find the bug; it improves the algorithm itself.

Common mistake

Testing only with normal inputs. Three tests for n = 5, n = 6, and n = 7 try the same region three times and show nothing new. n = 0, n = 20, n = −3, and n = 21, however, each answer a different question. A good test set is measured not by the number of tests but by the regions it covers.

4.1.5Algorithm analysis

For a problem there is often more than one correct algorithm. To choose among them, we need to measure how much work the algorithms do. This measurement is called algorithm analysis. The goal of analysis is not to measure time in seconds; that time varies with the computer, the programming language, and the other programs running at the moment. The goal is to find how the work done changes with the size of the input.

4.1.5.1One problem, two algorithms

The problem is to find the sum of the integers from 1 to n: 1 + 2 + … + n. The first algorithm that comes to mind (A) adds the numbers one by one with a loop:

sum = 0
i = 1
while i <= n
    sum = sum + i
    i = i + 1

The second algorithm (B) uses a formula attributed to Gauss and finds the result in a single step:

sum = n * (n + 1) / 2

Where the formula comes from is seen with a short computation. The sum is written twice, once from start to end and once from end to start:

T = 1 + 2 + 3 + … + n

T = n + (n − 1) + (n − 2) + … + 1

If the numbers lined up one under the other are added, every pair totals n + 1: 1 + n, 2 + (n − 1), … There are n pairs in all. So 2T = n × (n + 1), that is, T = n × (n + 1) / 2. For n = 10 this gives 10 × 11 / 2 = 55; the loop computation of 1 + 2 + … + 10 is also 55.

Number of additionsn = 10loop: 10 additionsformula: 1 addition + 1 multiplication + 1 division · result 55n = 100loop: 100 additionsformula: 1 addition + 1 multiplication + 1 division · result 5,050n = 1,000loop: 1,000 additionsformula: 1 addition + 1 multiplication + 1 division · result 500,500
Figure 4.1.15: The number of operations the two algorithms perform. As n grows, the loop's number of additions grows with n (10, 100, 1,000); the formula's operation count stays constant, independent of n.
Table 4.1.8: Result and operation count of the two algorithms for 1 + 2 + … + n. The results were computed by both methods and came out equal.
nResultA: additions in the loopB: operations in the formula
1055101 multiplication, 1 addition, 1 division
1005,0501001 multiplication, 1 addition, 1 division
1,000500,5001,0001 multiplication, 1 addition, 1 division
1,000,000500,000,500,0001,000,0001 multiplication, 1 addition, 1 division

Figure 4.1.15 and Table 4.1.8 show that both algorithms are correct, but that the work they do grows very differently. In A the loop runs n times; each iteration performs one addition and one counter increment. When n grows a thousandfold, A's work grows a thousandfold. B, whatever n is, performs one addition (n + 1), one multiplication, and one division. For the sum of a million numbers, A runs a million iterations; B still finishes with three operations.

4.1.5.2Correctness and efficiency

The summation example shows that two separate criteria are used when evaluating algorithms. Correctness means that the algorithm produces the expected result. Efficiency is how many resources the algorithm uses to reach that result. The two most important resources are time and memory.

Definition 4.1.7

Time complexity describes how the number of basic operations an algorithm performs changes with the input size. Space complexity describes how the amount of extra memory the algorithm uses, beyond the input itself, changes with the input size.

The input size is usually denoted by the letter n and chosen according to the nature of the problem. In an algorithm that searches or sorts an array, n is the number of elements in the array. In an algorithm that computes a factorial or a sum, n is the number entered itself. The basic operation is also chosen according to the problem. In searching and sorting algorithms, we usually count the number of comparisons between two elements, because comparisons make up most of the work.

Different inputs of the same size may require different amounts of work. If the value searched for in an array is the first element, the search ends immediately; if it is the last element, the whole array is examined. That is why three cases are considered separately. The best case is the input on which the algorithm does the least work. The worst case is the input on which it does the most work. The average case is the amount of work expected on random inputs. In practice the worst case is used most: it guarantees that the algorithm will be no slower than this bound on any input.

4.1.5.3Big-O notation

Counting operations exactly is often unnecessary. An algorithm performing 3n + 2 operations and one performing 5n grow in the same way: when n doubles, the work of both roughly doubles. What matters is not the coefficients but the shape of the growth. Big-O notation is a way of writing this shape concisely.

Definition 4.1.8

Big-O notation writes the fastest-growing term of an algorithm's operation count as n grows, dropping its coefficient. An algorithm performing 3n + 2 operations is O(n), and one making n(n − 1)/2 comparisons has complexity O(n²). An algorithm that performs a constant number of operations, independent of n, has complexity O(1).

The complexities met most often in this chapter are the following. O(1) is constant time: the Gauss formula performs three operations whatever n is. O(log n) is logarithmic time: at each step the problem is cut in half; binary search works this way. O(n) is linear time: each element is looked at once; summing with a loop and linear search are like this. O(n log n) is the complexity of merge sort. O(n²) is quadratic time: each element is compared with most of the other elements; selection, bubble, and insertion sort are like this in the worst case.

The expression log₂ n is the answer to the question “to what power must 2 be raised to get n?” Since 210 = 1,024, log₂ 1,024 = 10. There is also a more intuitive reading: log₂ n says how many times n must be halved to get down to 1. The number 1,000,000 falls below 1 after being halved 20 times. That is why logarithmic algorithms do little work even on very large inputs.

Table 4.1.9: Operation counts of different complexities as the input size n grows. The binary search column is the number of iterations for a value that is not found in a sorted array of n elements, and was counted by running the algorithm.
nBinary search (⌊log₂ n⌋ + 1 iterations)Linear search (n)Selection sort (n(n − 1)/2)n²
1041045100
10071004,95010,000
1,000101,000499,5001,000,000
1,000,000201,000,000499,999,500,0001,000,000,000,000

Table 4.1.9 shows the difference in numbers. At n = 10 the difference among the three columns is small; which method is chosen hardly matters. At n = 1,000,000, binary search finishes in 20 iterations, while linear search makes a million comparisons. Selection sort makes about five hundred billion comparisons. A computer that performs a billion comparisons per second finishes binary search in less than a millionth of a second, and selection sort in about eight minutes.

Efficiency is not always the only criterion. The method that looks fastest on small data is not always the easiest to understand. To sort a ten-element list, it is often wiser to choose a simple method that is easy to understand and verify than to write a complicated algorithm. As the input grows, the balance tips in favor of efficiency.

Common mistake

Mistaking Big-O notation for exact running time. It cannot be said that an O(n) algorithm is always faster than an O(n²) algorithm. The notation drops coefficients: an algorithm that performs 1,000n operations is O(n), but for n = 100 it performs 100,000 operations. An algorithm that performs n² operations finishes the same n with 10,000. Big-O tells which algorithm will pull ahead once n is large enough.

4.1.6Searching

The task of finding out whether a particular value is present in a collection of data, and where it is if so, is called searching. Finding a phone number in a directory, a number in a student list, or a word in a dictionary are all searches. The value being sought is called the target. The algorithms here search for a target in an integer array. If the target is found they return its index; if not, they return −1. Since −1 is never a valid index, it is a safe marker meaning “absent.”

The search algorithms are written in Java. In Java, int[] arr is an integer array; arr[i] is the element at index i and arr.length gives the number of elements. Indices start at 0; the last index of an array of n elements is n − 1. The return statement ends the method immediately and sends the value next to it back to the place that called the method.

4.1.6.1Linear search

The simplest search method is to look at the elements in order from start to end. Each element is compared with the target; when a match is found, the search ends. Scanning the shelves one by one to find a book among books arranged in no order in a library is similar to this method.

Definition 4.1.9

Linear search is a search method that compares the elements of an array with the target in order, starting from the first element, and returns the index of the first matching element. If no element matches, −1 is returned.

int linearSearch(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) return i;
    }
    return -1;
}

The method takes two parameters: the array to search and the target. The for loop increases i from 0 to arr.length − 1. On each iteration the comparison arr[i] == target is made. If they are equal, return i ends the method immediately; the rest of the loop does not run. If the loop ends without finding a match, control reaches the last line and −1 is returned.

Linear search has two important properties. First, the array does not need to be sorted; all elements are examined, in whatever order they are. Second, it stops at the first match. If the target occurs in the array more than once, the smallest index is returned.

0713293541 0713293541▲ i
Figure 4.1.16: Linear search for 5 in the array {7, 3, 9, 5, 1}. On the left is the initial state; on the right, 5 has been found at i = 3. The faded cells are elements that were compared with the target and did not match.
Table 4.1.10: Trace table of the call linearSearch(arr, 5); arr = {7, 3, 9, 5, 1}.
ii < arr.lengtharr[i]arr[i] == targetResult
00 < 5 → true77 == 5 → falsenext element
11 < 5 → true33 == 5 → falsenext element
22 < 5 → true99 == 5 → falsenext element
33 < 5 → true55 == 5 → truereturn 3

As Table 4.1.10 shows, 5 is found at the fourth element and the method returns 3; 4 comparisons were made. Had the target been 4, all five elements would be tried, none would match, and −1 would be returned after 5 comparisons. The method compiled and run with JDK 21 also gives 3 for linearSearch(arr, 5) and −1 for linearSearch(arr, 4).

The cost of linear search depends on the position of the target. In the best case the target is the first element and a single comparison is enough. In the worst case the target is the last element or is not in the array at all; n comparisons are made. That is why the time complexity of linear search is O(n). The only extra memory used is the variable i; the space complexity is O(1).

Common mistake

Reporting “not found” inside the loop. If else return -1; is added inside the loop, the method returns −1 right away when the first element is not the target and never looks at the remaining elements. −1 can be returned only after all elements have been tried, that is, after the loop ends.

4.1.6.2Binary search

When looking up a name in a phone book, one does not start at the first page and turn pages one by one. One opens a page somewhere in the middle. If the name sought comes before the one on that page alphabetically, one moves to the front half; if it comes after, to the back half. With every look, half of the book is eliminated. This method depends on the book being in alphabetical order. Its computer counterpart is binary search.

Definition 4.1.10

Binary search is a search method that, in a sorted array, compares the target with the element in the middle of the search range and at each step eliminates the half of the range in which the target cannot be. If the range becomes empty, the target is not in the array.

int binarySearch(int[] arr, int target) {
    int lo = 0, hi = arr.length - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (arr[mid] == target) return mid;
        if (arr[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

The lines of the method work as follows:

  1. int lo = 0, hi = arr.length - 1;: the search range is initially the whole array. lo is the first index of the range and hi the last.
  2. while (lo <= hi): the loop continues as long as at least one element remains in the range. If lo passes hi, the range is empty.
  3. int mid = lo + (hi - lo) / 2;: the index in the middle of the range is computed. In Java, the quotient of two integers is an integer; the fractional part is discarded: 7 / 2 = 3.
  4. if (arr[mid] == target) return mid;: if the middle element is the target, the search ends.
  5. if (arr[mid] < target) lo = mid + 1;: if the middle element is less than the target, then, because the array is sorted, all elements to the left of the middle are also less than the target. The left half is eliminated together with the middle.
  6. else hi = mid - 1;: otherwise the middle element is greater than the target; the right half is eliminated together with the middle.
  7. return -1;: if the range has become empty, the target is not in the array.

The elimination decision in lines 6 and 7 is the heart of the algorithm, and it rests entirely on the array being sorted. In a sorted array, if arr[mid] < target, then every one of arr[0], …, arr[mid] is less than the target; none of them can be the target. That is why the middle itself is also eliminated: lo becomes mid + 1, not mid.

There is a reason the middle index is computed as lo + (hi - lo) / 2 rather than (lo + hi) / 2. In mathematics the two expressions give the same result. On a computer, however, the int type holds at most 2,147,483,647. In a very large array, if lo = 1,500,000,000 and hi = 2,000,000,000, then lo + hi would exceed this limit and overflow. Tried with JDK 21, the expression (lo + hi) / 2 gives a negative index such as −397,483,648. lo + (hi - lo) / 2, on the other hand, finds the correct result, 1,750,000,000, because the difference of the two indices is taken first and the difference never exceeds the limit.

In the example here the array has nine elements and the target is 34. Each iteration of the algorithm is shown in Table 4.1.11 and Figure 4.1.17.

Table 4.1.11: Trace table of the call binarySearch(arr, 34); arr = {3, 8, 12, 17, 21, 25, 30, 34, 40}.
Roundlohimidarr[mid]Decision
1080 + (8 − 0) / 2 = 42121 < 34 → lo = 5
2585 + (8 − 5) / 2 = 63030 < 34 → lo = 7
3787 + (8 − 7) / 2 = 73434 == 34 → return 7
0318212317421525630734840▲ lo▲ hi▲ mid 0318212317421525630734840▲ lo▲ hi▲ mid 0318212317421525630734840▲ lo mid▲ hi
Figure 4.1.17: Finding 34 by binary search, three iterations (in order). Iteration 1: range 0…8, mid = 4, arr[4] = 21. Iteration 2: range 5…8, mid = 6, arr[6] = 30. Iteration 3: range 7…8, mid = 7, arr[7] = 34; the target is found. Faded cells are eliminated elements.

In the first iteration the middle element, 21, is less than 34; 21 and the four elements to its left are eliminated. In the second iteration the middle of the remaining four elements is 30, which is again less than the target; 30 and the 25 to its left are eliminated. In the third iteration two elements remain. 7 + (8 − 7) / 2 = 7, and arr[7] = 34 is found. Binary search has found the target in 3 iterations. Linear search would have made 8 comparisons to reach 34 in the same array.

4.1.6.3Binary search: when the target is absent

The aspect of binary search that is easiest to misunderstand is how it stops when the target is not in the array. To see this, we search for 19 in the eight-element array {3, 8, 12, 17, 21, 25, 30, 40}. 19 is not in the array; if it were, it would sit between 17 and 21, at position 4.

Table 4.1.12: Trace table of the call binarySearch(arr, 19); arr = {3, 8, 12, 17, 21, 25, 30, 40}.
Roundlohimidarr[mid]Decision
1070 + (7 − 0) / 2 = 31717 < 19 → lo = 4
2474 + (7 − 4) / 2 = 52525 > 19 → hi = 4
3444 + (4 − 4) / 2 = 42121 > 19 → hi = 3
—43——4 ≤ 3 → false: the range is empty, return −1
0318212317421525630740▲ lo▲ mid▲ hi 0318212317421525630740▲ lo▲ mid▲ hi 0318212317421525630740▲ lo mid hi 0318212317421525630740▲ hi▲ lo
Figure 4.1.18: Binary search failing to find 19. Iteration 1: mid = 3, arr[3] = 17 < 19, the left half is eliminated. Iteration 2: mid = 5, arr[5] = 25 > 19, the right half is eliminated. Iteration 3: the range is a single element (4), arr[4] = 21 > 19, and hi becomes 3. In the final state hi is to the left of lo; the range is empty.

After the third iteration, lo = 4 and hi = 3. lo and hi have crossed; that is, lo has passed hi. Since the condition 4 ≤ 3 is false, the loop ends and −1 is returned. The algorithm has given the answer “absent” in 3 iterations; it did not look at all eight elements one by one. The value of lo at the moment the loop ends is also meaningful: 4 is the position where the target would be found if it were in the array.

Java's own library uses this information. When the target is not found, the java.util.Arrays.binarySearch method returns −(insertion point) − 1 instead of −1. For 19 in the same array, the value JDK 21 returns is −5: −4 − 1 = −5. Because the value is negative, the meaning “not found” is preserved; in addition, we learn at which position the target should be inserted.

Example 4.1.7

What happens if binary search is run for 5 on the unsorted array {7, 3, 9, 5, 1}?

Iteration 1: lo = 0, hi = 4, mid = 2, arr[2] = 9. Since 9 > 5, the right half is eliminated and hi becomes 1. The 5 is in fact on the eliminated side, at position 3. Iteration 2: lo = 0, hi = 1, mid = 0, arr[0] = 7. Since 7 > 5, hi becomes −1. 0 ≤ −1 is false and −1 is returned. Although 5 is in the array, it has not been found. binarySearch run with JDK 21 also gives −1 for this array.

The algorithm raises no error and does not enter an infinite loop; it simply gives a wrong answer. This makes the bug more dangerous. Eliminating half is safe only if the array is sorted.

The cost of binary search is measured by the number of iterations. On each iteration the number of elements in the range falls to slightly less than half, because the middle is eliminated too. In an array of n elements the range becomes empty in at most ⌊log₂ n⌋ + 1 iterations. In an eight-element array the bound is ⌊log₂ 8⌋ + 1 = 3 + 1 = 4 iterations; the search for 19 ended in 3. In an array of a million elements the bound is 20 iterations. That is why the time complexity of binary search is O(log n). The extra memory requirement consists of the variables lo, hi, and mid; the space complexity is O(1).

Common mistake

Writing the loop condition as lo < hi, or updating the bounds as lo = mid and hi = mid. The first mistake means that when a single element remains in the range (lo = hi), that element is never looked at; at the end of the search for 3 in a 9-element array such a situation arises and the target is missed. The second mistake, because the middle is not eliminated, means the range sometimes never shrinks and the loop goes on forever. The correct form is the condition lo <= hi with the updates mid + 1 and mid - 1.

4.1.6.4Comparing search methods

The two search methods suit different conditions. Table 4.1.13 summarizes the differences.

Table 4.1.13: Comparison of linear and binary search.
PropertyLinear searchBinary search
Sorted dataNot requiredRequired
Best case1 comparison (target is the first element)1 iteration (target is in the middle)
Worst-case timeO(n)O(log n)
Extra memoryO(1)O(1)
StructureAn array, or a data stream read from start to endA sorted structure with random access
Suitable useLittle or unsorted data, a single searchMany searches on the same data

The “structure” row of the table points out a detail. Binary search depends on being able to reach the element in the middle of the array directly on each iteration. Reaching an element by its index in a single step, without passing through the ones before it, is called random access. Arrays have random access. In data that arrives in order from a file or a network, however, reaching the middle element requires reading all the earlier elements; for such data, linear search is the only option.

Linear12345678910111213141516the target is the last element: all 16 elements are examined → 16 comparisonsBinary12345the range halves at each step: 16 → 8 → 4 → 2 → 1 ⇒ 5 comparisons
Figure 4.1.19: Searching for the last element in a sorted array of 16 elements. Linear search looks at all 16 elements. The elements binary search looks at are numbered in order: the range narrows 16 → 8 → 4 → 2 → 1 and 5 comparisons are enough.

Figure 4.1.19 shows the elements the two methods look at for the same target. When the array has 16 elements and the target is the last element, binary search looks at the 8th, 12th, 14th, 15th, and 16th elements in turn. Even in this small example the difference is more than threefold. The gap widens quickly as the array grows.

016324864016324864array size nworst-case comparisonslinear (64)binary (7)
Figure 4.1.20: The number of comparisons in the worst case for a target that is not found. Linear search makes n comparisons (64 for n = 64); binary search makes ⌊log₂ n⌋ + 1 iterations (7 for n = 64). The values were counted by actually running the two algorithms.

Figure 4.1.20 plots how the gap grows. The curve of linear search is a straight line; when n doubles, the number of comparisons doubles. The curve of binary search rises step by step, very slowly: when n doubles, the number of iterations increases by only one. For n = 1,000,000, linear search makes a million comparisons and binary search only 20.

This superiority has a price: binary search needs sorted data. If the data is not sorted, it must be sorted first. Sorting is a much more expensive task than searching itself; even the best general-purpose methods take O(n log n) time. For a single search, sorting first and then running binary search is more expensive than simply running linear search. If thousands of searches will be made on the same data, however, sorting once pays for itself quickly.

Example 4.1.8

500 searches will be made in an unsorted array of 1,000 elements. What are the worst-case comparison counts for linear search and for “selection sort first, then binary search”?

Linear search makes at most 1,000 comparisons per search: 500 × 1,000 = 500,000. Selection sort makes 1,000 × 999 / 2 = 499,500 comparisons for 1,000 elements. After that, each binary search takes at most ⌊log₂ 1,000⌋ + 1 = 10 iterations: 500 × 10 = 5,000. The total is 499,500 + 5,000 = 504,500. At this number of searches the two routes are almost equal. If the number of searches increases, the sorting route pulls ahead; if a faster sorting method is chosen, the gap opens much earlier.

4.1.7Sorting

Arranging the elements of a collection in a particular order, for example from smallest to largest, is called sorting. Sorting is one of the things computers do most. Exam results are sorted by score, e-mails by date, products by price. Another value of sorting is that it makes later tasks easier: binary search works only on sorted data.

Four methods are compared here. The first three, selection, bubble, and insertion sort, are easy to understand and can be traced by hand. All three make O(n²) comparisons in the worst case. The fourth, merge sort, rests on a different idea and is much faster on large arrays. All methods sort the array from smallest to largest. Two elements standing side by side in an array are called adjacent elements.

4.1.7.1Selection sort

A person sorting the cards in their hand can first find the smallest and put it at the front, then find the smallest among the rest and put it second. This natural method is called selection sort.

Definition 4.1.11

Selection sort is a sorting method that finds the smallest element in the unsorted part and swaps it with the element at the first position of that part. This step is repeated until one element remains in the unsorted part.

for i = 0 to n-2
    minIdx = i
    for j = i+1 to n-1
        if arr[j] < arr[minIdx] then minIdx = j
    swap arr[i] and arr[minIdx]

Each iteration of the outer loop is called a pass. At the start of pass i, the part 0…i − 1 of the array is sorted and holds the i smallest elements; the part i…n − 1 is unsorted. The variable minIdx is the index of the smallest element found so far. At the start, the first element of the unsorted part is taken as the smallest. The inner loop compares the rest of the part, one by one, with the element at minIdx; when a smaller one is found, minIdx is updated. When the inner loop finishes, the smallest element is swapped with the element at position i, and the sorted part grows by one element.

i = 02910143713iminIdxswapafter1029143713sorted | unsortedsmallest (10) found
Figure 4.1.21: The first pass of selection sort: in the array {29, 10, 14, 37, 13} the smallest element is 10, and it is swapped with the 29 at position 0. At the end of the pass, 10 is in the sorted part; the remaining four elements are unsorted.

The example array here is {29, 10, 14, 37, 13}. The result of each pass is given in Table 4.1.14.

Table 4.1.14: Trace table of selection sort for {29, 10, 14, 37, 13}. The “new values of minIdx” column shows, in order, the elements found smaller in the inner loop.
PassUnsorted partComparingNew values of minIdxSwapArray at end of pass
i = 00…4410 (arr[1])arr[0] ↔ arr[1][10, 29, 14, 37, 13]
i = 11…4314 (arr[2]), 13 (arr[4])arr[1] ↔ arr[4][10, 13, 14, 37, 29]
i = 22…42unchangedin place (no effect)[10, 13, 14, 37, 29]
i = 33…4129 (arr[4])arr[3] ↔ arr[4][10, 13, 14, 29, 37]

The rows of the table read as follows. At i = 0 the candidate smallest is 29. arr[1] = 10 is smaller and minIdx = 1; 14, 37, and 13 are not smaller than 10. 10 is moved to the front. At i = 1 the candidate is 29. First 14 is found (minIdx = 2), then 13 is smaller still (minIdx = 4). 13 and 29 are swapped. At i = 2 the candidate is 14, and the remaining 37 and 29 are not smaller; the smallest is already in place. In this pass the algorithm “swaps” arr[2] with itself; the operation has no effect. At i = 3, 29 and 37 are swapped and the array is sorted.

010129214337413▲ i▲ minIdx 010113214337429▲ i▲ minIdx 010113214337429▲ iminIdx 010113214329437▲ i▲ minIdx
Figure 4.1.22: The end of the four passes of selection sort. i = 0: arr[0] and arr[1] are swapped. i = 1: arr[1] and arr[4] are swapped. i = 2: the smallest is already in place (minIdx = i). i = 3: arr[3] and arr[4] are swapped. Cells with a green frame are the sorted part.

The number of comparisons does not depend at all on the contents of the array. At i = 0 the inner loop makes n − 1 comparisons, at i = 1 it makes n − 2, …, and in the last pass 1. The total:

(n − 1) + (n − 2) + … + 1 = n(n − 1) / 2

This is the Gauss formula with n − 1 in place of n. For n = 5 it comes to 4 + 3 + 2 + 1 = 10 comparisons; the trace shown here also counted 10 comparisons. Even if the array is already sorted, the algorithm searches for the smallest again on every pass and still makes 10 comparisons. That is why selection sort is O(n²) in both the best case and the worst case. On the other hand, the number of swaps is small: at most one swap per pass, at most n − 1 in total. Only a few helper variables are needed; the space complexity is O(1).

Common mistake

Keeping the value of the smallest element in the inner loop instead of its index. The value is known, but if its place in the array is not known, the swap cannot be done. minIdx is an index; the comparison is made in the form arr[j] < arr[minIdx]. Another mistake is to put the swap inside the inner loop: in that case a swap is made every time a smaller element is found, and the number of swaps rises needlessly.

4.1.7.2Bubble sort

Bubble sort compares only elements that stand side by side. In one pass the array is scanned from left to right, and every adjacent pair that is in the wrong order is swapped. Large values rise toward the right on every pass, like bubbles in water.

Definition 4.1.12

Bubble sort is a sorting method that compares adjacent elements from left to right and swaps every pair that is in the wrong order. Passes are repeated until a pass makes no swap at all.

round = 0
repeat
    swapped = false
    for j = 0 to n-2-round
        if arr[j] > arr[j+1] then
            swap arr[j] and arr[j+1]
            swapped = true
    round = round + 1
until swapped is false

At the end of a pass, the largest of the remaining elements has definitely reached the far right. The reason is this: wherever the largest element is, it wins every comparison with its right-hand neighbor and moves one place to the right. That is why each pass is one element shorter than the previous one. The variable round holds the number of completed passes and shortens the bound of the inner loop to n − 2 − round.

The variable swapped provides the algorithm's early stopping property. It is set to false at the start of every pass; if a swap happens in the pass, it becomes true. If no swap has happened in a pass, all adjacent pairs are in the right order, that is, the array is sorted. In that case no further pass is made and the algorithm stops. Writing the loop in the form “repeat … until” shows that the condition is checked after the body: the body runs at least once.

Table 4.1.15: Trace table of bubble sort for {5, 1, 4, 2, 8}. The ↔ sign shows that the pair was swapped.
PassjPairs compared (↔ swap)ComparingArray at end of passswapped
Pass 10…3(5, 1)↔ (5, 4)↔ (5, 2)↔ (5, 8)4[1, 4, 2, 5, 8]true
Pass 20…2(1, 4) (4, 2)↔ (4, 5)3[1, 2, 4, 5, 8]true
Pass 30…1(1, 2) (2, 4)2[1, 2, 4, 5, 8]false

Table 4.1.15 shows the three passes on the array {5, 1, 4, 2, 8}. In pass 1, 5 moves to position 3 by swapping in turn with 1, 4, and 2. When it is compared with 8, the order is right; 8 is already the largest and is at the far right. At the end of the pass, 8 is definitely in its place. In pass 2, only 4 and 2 are swapped and the array becomes sorted. The algorithm does not yet know this: swapped is true, so one more pass is made. In pass 3 no swap happens; swapped stays false and the algorithm stops. In total 4 + 3 + 2 = 9 comparisons were made.

0115243248▲ j▲ j+1 0114223548 0112243548 0112243548
Figure 4.1.23: Four moments from bubble sort: the first swap in pass 1 (5 with 1); the end of pass 1 (8 in place); the end of pass 2 (5 also in place); the end of pass 3 (no swap happened, the array is sorted). Cells with a green frame are elements that have settled into their final places.

The cost of bubble sort depends on the input. In the worst case, when the array is in reverse order, every pair is swapped on every pass and n − 1 passes are needed. The number of comparisons, as in selection sort, is n(n − 1)/2; the time complexity is O(n²). In the best case the array is already sorted. In the first pass n − 1 comparisons are made, no swap happens, and the algorithm stops: O(n). Without early stopping, the algorithm would make all the passes needlessly even on a sorted array. The extra memory is O(1).

Common mistake

Running the inner loop up to n - 1 - round. Because the comparison is made between arr[j] and arr[j+1], the largest value of j is the left element of the last pair to be compared. In the first pass this index is n − 2. If j goes up to n − 1, arr[j+1] falls outside the array; in this case Java throws an ArrayIndexOutOfBoundsException.

4.1.7.3Insertion sort

In card games, players usually arrange the cards in hand like this: when a new card is picked up, the right place is found among the cards already sorted in the hand, and the card is slipped in there. Insertion sort is exactly this method.

Definition 4.1.13

Insertion sort is a sorting method that always keeps the left part of the array sorted, takes the next element on the right (the key), and places it into the gap opened by shifting the elements greater than it one position to the right.

for i = 1 to n-1
    key = arr[i]
    j = i - 1
    while j >= 0 and arr[j] > key
        arr[j+1] = arr[j]
        j = j - 1
    arr[j+1] = key

The outer loop starts i at 1, because a part with one element (0…0) is already sorted. On each iteration the key is taken from arr[i]; the key's place can now be considered a “gap.” j starts at the element to the left of the key. The inner loop continues on two conditions: j must be inside the array (j ≥ 0) and arr[j] must be greater than the key. As long as the condition holds, arr[j] is shifted one place to the right and j decreases by one; the gap moves to the left. When the loop stops, the gap is at position j + 1 and the key is written there.

sorted partkey245323455 > 3 and 4 > 3: shift each one right2 > 3 is false: stop3 settles into the gap
Figure 4.1.24: One step of insertion sort. The sorted part is {2, 4, 5} and the key is 3. Since 5 > 3 and 4 > 3, both shift one place right; since 2 > 3 is false, we stop. 3 settles into the gap: {2, 3, 4, 5}.

It matters that the check j >= 0 comes first in the condition. When j = −1 this condition is false. The word “and” does not look at the second condition if the first is false; arr[−1] is never read. If the order of the two conditions is swapped, arr[−1] is read when the key is about to be placed at the very front, and the program fails.

Table 4.1.16: Trace table of insertion sort for {4, 3, 5, 1}. ✓ is a comparison where the condition arr[j] > key came out true (the element is shifted), ✗ one where it came out false (the loop stops).
StepkeyComparisonsKeyShiftsIndex where placedArray after
i = 134 > 3 ✓ (j = −1, stops)110[3, 4, 5, 1]
i = 254 > 5 ✗102[3, 4, 5, 1]
i = 315 > 1 ✓, 4 > 1 ✓, 3 > 1 ✓ (j = −1, stops)330[1, 3, 4, 5]

Table 4.1.16 is the trace of the array {4, 3, 5, 1}. At i = 1 the key is 3; since 4 > 3, 4 shifts right, j = −1, and the loop stops because it has reached the left end. 3 is placed at position 0. At i = 2 the key is 5; the 4 to its left is smaller, so its place is found with a single comparison and no shifting is done. At i = 3 the key, 1, is smaller than all the elements. 5, 4, and 3 shift right in turn and 1 is placed at the very front. In total 1 + 1 + 3 = 5 comparisons were made.

03142531 03142531 0314235key1shift right 01132435
Figure 4.1.25: Four moments from insertion sort: at the end of i = 1, 3 has been placed; at the end of i = 2, 5 has been placed without shifting; at i = 3, for key 1, 5 shifts right; at the end of i = 3, 1 has been placed at the front and the array is sorted. Cells with a green frame are the sorted part.

The cost of insertion sort depends on how far the elements are “out of place.” In the worst case the array is in reverse order; every key is shifted all the way to the front of the sorted part and n(n − 1)/2 comparisons are made: O(n²). In the best case the array is already sorted; for each key a single comparison is made and there is no shifting. A total of n − 1 comparisons: O(n). The extra memory is just the key and j variables: O(1).

This property makes insertion sort valuable in practice. It runs very fast on arrays with few elements or that are nearly sorted. In situations where new records are occasionally added to a sorted list, for example an alphabetical list to which a few students are added every day, insertion sort is a natural choice.

Common mistake

Starting to shift without saving the key in a variable. The first shift is the assignment arr[i] = arr[i-1], and it erases the value in arr[i]. If the key has not been copied into the key variable beforehand, this value is lost. The situation is the same as the temporary variable in a swap: a value that is about to be overwritten is saved first.

4.1.7.4Merge sort

The previous three methods place elements one at a time and make O(n²) comparisons. Merge sort rests on a different idea: merging two sorted arrays into a single sorted array is very cheap. The smallest element of two sorted arrays is the smaller of their two first elements. That element is taken, and the same comparison is repeated for the remaining elements. Each comparison adds one element to the result; if the total number of elements is m, at most m − 1 comparisons are enough.

The algorithm uses this merge operation as follows. The array is split in the middle into two halves. Each half is sorted separately by the same method. Then the two sorted halves are merged. The halves are split again and again until they come down to arrays of one element; an array of one element is already sorted. Splitting a problem into smaller problems of the same kind and combining their solutions is called the divide and conquer approach.

merge(A, B):
    C = empty array
    i = 0, j = 0
    while i < A.length and j < B.length
        if A[i] ≤ B[j] then append A[i] to C, i = i + 1
        else append B[j] to C, j = j + 1
    append the remaining elements of A and B to C in order
    return C

sort(arr):
    if arr has at most 1 element return arr
    split arr in the middle into two halves: left and right
    return merge(sort(left), sort(right))

The sort operation calls itself again for smaller arrays. Such an operation, which is reused in its own definition, is called recursive. A detailed understanding of recursion is not needed for this chapter; what matters is that the splitting stops when it reaches arrays of one element, and that the merge at each level passes its result up to the next level.

Example 4.1.9

How is the array {38, 27, 43, 3, 9, 82, 10, 5} sorted by merge sort? How many comparisons are made?

The array is first split into the halves {38, 27, 43, 3} and {9, 82, 10, 5}, these into pairs, and finally into single elements. The merges are then done from the bottom up:

Two sorted parts mergedResultComparing
[38] + [27][27, 38]1
[43] + [3][3, 43]1
[27, 38] + [3, 43][3, 27, 38, 43]3
[9] + [82][9, 82]1
[10] + [5][5, 10]1
[9, 82] + [5, 10][5, 9, 10, 82]3
[3, 27, 38, 43] + [5, 9, 10, 82][3, 5, 9, 10, 27, 38, 43, 82]7
Total17

In the final merge, the parts {3, 27, 38, 43} and {5, 9, 10, 82} merge like this: 3 < 5 → 3; 27 > 5 → 5; 27 > 9 → 9; 27 > 10 → 10; 27 < 82 → 27; 38 < 82 → 38; 43 < 82 → 43. The left part is used up; the remaining 82 is appended without a comparison. 8 elements have been merged with 7 comparisons. Over all the merges, 17 comparisons are made in total. For the same array, selection sort would make 8 × 7 / 2 = 28 comparisons.

The cost of merge sort comes from the number of levels. Because the array is halved at every level, there are log₂ n levels; 3 levels for 8 elements. At each level all the elements go through a merge once, and at most n comparisons are made. The total number of comparisons is about n × log₂ n; the time complexity is O(n log n) in the best, average, and worst cases. The price is memory: the result of a merge is built in a separate array. So the extra memory is O(n).

4.1.7.5Comparing sorting methods

Table 4.1.17: Comparison of the four sorting methods.
AlgorithmBasic ideaWorst caseBest caseExtra space
SelectionSelect the smallest and place itO(n²)O(n²)O(1)
BubbleSwap neighborsO(n²)O(n) (with early stopping)O(1)
InsertionInsert the element into the sorted partO(n²)O(n)O(1)
MergeSplit, sort, mergeO(n log n)O(n log n)O(n)

Table 4.1.17 summarizes the four methods in terms of complexity. Even methods with the same Big-O value actually make different numbers of comparisons. Table 4.1.18 counts them by running the three simple methods on the same five-element arrays.

Table 4.1.18: Numbers of comparisons and swaps on three five-element arrays (comparisons / swaps). In insertion sort the second number is the number of shifts; in selection sort only swaps that actually move elements are counted.
Input (n = 5)SelectionBubble (with early stopping)Insertion
Sorted [1, 2, 3, 4, 5]10 / 04 / 04 / 0
Reverse sorted [5, 4, 3, 2, 1]10 / 210 / 1010 / 10
Shuffled [5, 1, 4, 2, 8]10 / 29 / 47 / 4

The table confirms the “best case” column of the complexity table with numbers. On a sorted array, selection sort still makes 10 comparisons; bubble and insertion sort finish the job with 4. On a reverse-sorted array all three methods make 10 comparisons, but selection sort gets by with just 2 swaps. That selection sort makes few swaps is an advantage when writing is expensive.

0600120018000102030405060array size naverage comparisonsSelection (1770)Bubble (1739)Insertion (955)Merge (281)
Figure 4.1.26: The average number of comparisons on random arrays. For each n, 20 random arrays were sorted with the four algorithms and the averages are plotted. At n = 60, selection made 1,770, bubble 1,739, insertion 955, and merge 281 comparisons.

Figure 4.1.26 shows the average behavior on random arrays. Selection and bubble sort make about n² / 2 comparisons; for n = 60, selection makes exactly 60 × 59 / 2 = 1,770. Insertion sort on average makes about half of that, around n² / 4. The reason is that in a random array each key passes over about half of the sorted part on average. Merge sort stays around n log₂ n, and the gap opens quickly as n grows. In the computation for this chapter, an average over 2,000 random arrays gave, for n = 60, about 1,730 for bubble sort, 939 for insertion sort, and 281 for merge sort; the 20-array averages in the figure are close to these values.

In practice, ready-made library methods are used. Java's java.util.Arrays.sort method uses sophisticated methods that run in O(n log n) time. The method used on arrays of objects (Timsort) combines ideas from merge sort and insertion sort. On arrays of primitive types such as int, dual-pivot quicksort is used. Both methods switch to insertion sort on small pieces of the array, because insertion sort is fast on small and nearly sorted data. The value of learning the simple methods is that it lets us understand the reasons for these design decisions.

Seeing how sorting algorithms work complements the trace tables. The Sorting Algorithm Visualizer runs the four methods step by step on random, sorted, reverse-sorted and nearly sorted arrays and shows the comparison counts.

4.1.8Summary

  • Problem solving does not begin with code: the problem is understood, a small example is solved by hand, the method is written down, and only then is it coded. A problem definition consists of the goal, input, output, constraint, example, and error case.
  • An algorithm is a finite sequence of well-defined steps for solving a problem; it takes zero or more inputs and produces at least one output. The steps of a good algorithm are definite, ordered, and feasible; the algorithm stops in a finite number of steps, gives the right result for every valid input, and uses resources efficiently.
  • Algorithm design is a cycle: solve an example, find the general rule, write pseudocode, trace by hand, fix. Pseudocode writes an algorithm without tying it to a particular language; indentation shows the scope of conditions and loops.
  • A swap of two variables takes three assignments and a temporary variable. The order of assignments in Fibonacci matters for the same reason: a value that is about to be overwritten is first used or saved.
  • The starting value of an accumulator, which builds up a result step by step, is chosen according to the operation: 0 for a sum, 1 for a product. The loop invariant of the factorial algorithm is “at the start of each iteration, result = (i − 1)!”, and it explains why the algorithm is correct.
  • Palindrome checking moves from both ends toward the middle and makes at most ⌊n / 2⌋ comparisons. Primality checking searches for divisors only up to √n (i × i ≤ n). Both algorithms stop early as soon as the result is known.
  • Hand tracing and the trace table show that an algorithm works for one input. Test cases cover normal, boundary, invalid, and large inputs. A single successful test does not prove that an algorithm is correct for every input; the 21! test exposes overflow and a missing constraint check.
  • Time complexity describes how the number of operations grows with the input size, and space complexity how the extra memory grows; both are written in Big-O notation: O(1), O(log n), O(n), O(n log n), O(n²). The sum 1 + 2 + … + n is found in O(n) time with a loop and in O(1) time with the Gauss formula.
  • Linear search does not require sorting and makes n comparisons in the worst case: O(n). Binary search works only on sorted data, halves the range on every iteration, and makes at most ⌊log₂ n⌋ + 1 iterations: O(log n). At n = 1,000,000 the difference is 1,000,000 against 20.
  • Selection sort picks the smallest on every pass; it always makes n(n − 1)/2 comparisons but at most n − 1 swaps. Bubble sort swaps neighbors and stops on a pass with no swaps. Insertion sort inserts the key into the sorted part; it is very fast on nearly sorted data. All three are O(n²) in the worst case and O(1) in extra space.
  • Merge sort splits the array in two, sorts the halves, and merges them; in every case it uses O(n log n) time and O(n) extra memory.

4.1.9Key terms

The key terms of this chapter are listed below.

  • problem solving
  • problem definition
  • constraint
  • algorithm
  • definiteness
  • finiteness
  • correctness
  • pseudocode
  • indentation
  • swap
  • temporary variable
  • factorial
  • accumulator
  • loop invariant
  • off-by-one error
  • sliding window
  • palindrome
  • prime number
  • divisor
  • remainder
  • hand tracing
  • trace table
  • test case
  • invalid input
  • overflow
  • time complexity
  • space complexity
  • input size
  • Big-O notation
  • best case
  • worst case
  • search
  • target
  • linear search
  • binary search
  • search range
  • random access
  • sorting
  • sorted
  • adjacent
  • pass
  • selection sort
  • bubble sort
  • insertion sort
  • key
  • merge sort

4.1.10Test Yourself

  1. The algorithm that orders three numbers (first compare a–b, then b–c, finally a–b again) is run for a = 4, b = 9, c = 2. What are a, b, c after each comparison? How many swaps are made?

    Answer

    1st comparison: 4 > 9 is false; no change (4, 9, 2). 2nd comparison: 9 > 2 is true; b and c are swapped (4, 2, 9). 3rd comparison: 4 > 2 is true; a and b are swapped (2, 4, 9). The output is “2 4 9”; two swaps were made.

  2. In the algorithm that sums the even numbers, i = 1 was mistakenly written instead of i = 2; the increment is still i = i + 2. What is printed for n = 10? Which test catches the error?

    Answer

    The counter takes the values 1, 3, 5, 7, 9 and the odd numbers are summed: 1 + 3 + 5 + 7 + 9 = 25. The correct answer is 30. The test n = 1 also shows the error: 0 is expected and 1 is found. The test n = 0 does not show the error, because in both versions the loop never runs and 0 is printed.

  3. The prime algorithm is run for n = 97. Which values of i are tried, how many times is the % operation performed, and what is the result?

    Answer

    The 8 values from i = 2 to 9 are tried, because 9 × 9 = 81 ≤ 97 but 10 × 10 = 100 > 97. The remainders are 1, 1, 1, 2, 1, 6, 1, 7 in order; none is 0. The % operation is performed 8 times and “prime” is printed.

  4. The palindrome algorithm is run on the texts “Kalem” and “Kepek” (Turkish for “pencil” and “dandruff”). How many comparisons are made for each, and what is the result?

    Answer

    Lowercased, “Kalem” becomes “kalem.” In the first comparison text[0] = 'k' and text[4] = 'm' differ; after 1 comparison false is returned. For “Kepek,” k with k, then e with e are the same; when lo = hi = 2 the loop ends. With 2 comparisons true is returned.

  5. In the array {4, 8, 15, 16, 23, 42}, 16 is searched for first by linear search and then by binary search. How many comparisons or iterations does each method make? In binary search, what are lo, hi, and mid on each iteration?

    Answer

    Linear search looks at 4, 8, 15, and 16; after 4 comparisons it returns 3. Binary search: iteration 1: lo = 0, hi = 5, mid = 2, arr[2] = 15 < 16 → lo = 3. Iteration 2: lo = 3, hi = 5, mid = 4, arr[4] = 23 > 16 → hi = 3. Iteration 3: lo = hi = 3, mid = 3, arr[3] = 16 → 3 is returned. Binary search finds it in 3 iterations.

  6. A value that is not present is searched for in a sorted array of 4,000 elements. How many iterations does binary search make at most? If the array grows to 8,000 elements, how does the worst-case work of linear search and of binary search change?

    Answer

    Since 211 = 2,048 ≤ 4,000 < 4,096 = 212, ⌊log₂ 4,000⌋ = 11; binary search makes at most 11 + 1 = 12 iterations. When the array doubles, linear search's work also doubles (from 4,000 to 8,000 comparisons). The number of iterations of binary search increases by only one, to 13.

  7. The array [3, 1, 2, 4] is sorted with selection sort, bubble sort with early stopping, and insertion sort. How many comparisons does each method make? How many passes does bubble sort make?

    Answer

    Selection: 3 + 2 + 1 = 6 comparisons; the contents of the array do not change the result. Bubble: in pass 1, (3, 1) and (3, 2) are swapped and (3, 4) is in the right order; 3 comparisons, and the array becomes [1, 2, 3, 4]. In pass 2, 2 comparisons are made, no swap happens, and the algorithm stops. In total 2 passes and 5 comparisons. Insertion: for key 1, 1 comparison (3 > 1, then j = −1); for key 2, 2 comparisons (3 > 2, 1 > 2 is false); for key 4, 1 comparison; a total of 4. Because the array is nearly sorted, insertion sort makes the fewest comparisons.

  8. What are at least five test cases for the palindrome algorithm, and the expected result for each? Which possible bug does each test catch?

    Answer

    A sample test set: the empty text → true (the loop never runs; the algorithm must not crash). A single letter, “a” → true. An even-length palindrome, “abba” → true (lo and hi cross in the middle). A palindrome with a capital letter, “Kayak” → true (comes out false if the cleaning rule is not applied). A text containing Turkish I, “Iı” → true (comes out false if I is converted to i). A text that is not a palindrome, “kayık” → false. A text whose last letter differs, “kayaz” → false (must stop at the first comparison).

  9. An algorithm takes 2 seconds for n = 1,000. About how long is it expected to take for n = 2,000? How would the answer change if the algorithm were O(n), O(n²), or O(log n)?

    Answer

    In an O(n) algorithm the work grows in proportion to n; when n doubles, the time roughly doubles: 4 seconds. In an O(n²) algorithm the work grows with the square of n; it grows by a factor of 2² = 4: about 8 seconds. In an O(log n) algorithm, doubling n increases log₂ n by only 1 (from about 10 to 11); the time increases by about 10% and stays around 2.2 seconds. These are rough estimates; Big-O ignores coefficients and smaller terms.

4.1.11Further reading

  • R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), 4.1 Performance and 4.2 Sorting and Searching: measuring operation counts by experiment, binary search, and the simple sorting methods with Java examples; the book's site (introcs.cs.princeton.edu) has chapter summaries and code.
  • R. Sedgewick, K. Wayne, Algorithms (4th ed., Addison-Wesley, 2011), Chapter 2: compares selection, insertion, and merge sort with visual traces; the animations on the book's site (algs4.cs.princeton.edu) complement the trace tables in this chapter.
  • A. Levitin, Introduction to the Design and Analysis of Algorithms (3rd ed., Pearson, 2012), Chapters 1–3: treats the notion of an algorithm, problem definition, and brute-force methods (selection and bubble sort, linear search) in plain language.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms (4th ed., MIT Press, 2022), Chapter 2: gives the loop invariant and the correctness proof through insertion sort, and the analysis of merge sort, rigorously; for those who want to continue the subject at an advanced level.

4.1.12References

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022.
  2. A. Levitin, Introduction to the Design and Analysis of Algorithms, 3rd ed., Pearson, 2012.
  3. R. Sedgewick, K. Wayne, Algorithms, 4th ed., Addison-Wesley, 2011. Book site.
  4. R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 4.1 Performance, 4.2 Sorting and Searching.
  5. Oracle, Java SE 21 API: java.util.Arrays (sort, binarySearch).

Related pages: Chapter 4.1 slides · Study questions · Sorting Algorithm Visualizer · Flowchart Runner · Glossary · © Sercan Külcü. All rights reserved.