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.
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.
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.
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:
| Element | Answer for the factorial problem |
|---|---|
| Goal | Compute the factorial of the given number n |
| Input | An integer n |
| Output | The value of n! |
| Constraint | 0 ≤ n ≤ 20 (the result will be held in the 64-bit long type) |
| Example | 120 for n = 5; 1 for n = 0 |
| Error case | If 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.
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.
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.
| Property | Meaning | What happens when it fails |
|---|---|---|
| Definiteness | Every step is clear and has a single meaning | Different people carry out a step like “enlarge it a bit” differently |
| Ordering | The order in which steps are performed is fixed | If the order of assignments in a swap changes, a value is lost |
| Feasibility | Every step can actually be carried out | The step “list all prime numbers” can never be completed |
| Finiteness | The algorithm stops after a finite number of steps | The loop condition never becomes false, so the program never stops |
| Correctness | Produces the right result for every valid input | The program gives a wrong result on some inputs |
| Efficiency | Resource use stays acceptable as the input grows | A 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.
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.
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.
The five steps in Figure 4.1.4 work as follows:
- Solve an example. A small instance of the problem is solved by hand. For the factorial, we compute 4! = 1 × 2 × 3 × 4 = 24.
- 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.”
- Write pseudocode. The rule is turned into clear steps that are close to a programming language but not tied to one.
- 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.
- 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.
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
ENDThe 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.
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.
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, bLine 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.
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.
| Step | Line executed | a | b | temp |
|---|---|---|---|---|
| 1 | read a, b | 7 | 3 | — |
| 2 | if 7 > 3 then | 7 | 3 | — |
| 3 | temp = a | 7 | 3 | 7 |
| 4 | a = b | 3 | 3 | 7 |
| 5 | b = temp | 3 | 7 | 7 |
| 6 | print a, b → 3 7 | 3 | 7 | 7 |
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.
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.
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| Step | Condition | Result | a | b | c |
|---|---|---|---|---|---|
| start | — | — | 8 | 5 | 1 |
| 1st comparison | a > b | true → a and b are swapped | 5 | 8 | 1 |
| 2nd comparison | b > c | true → b and c are swapped | 5 | 1 | 8 |
| 3rd comparison | a > b | true → a and b are swapped | 1 | 5 | 8 |
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 resultThe lines do the following:
read n: the number whose factorial is to be computed is read.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.result = 1: the starting value of the product is 1. The variable builds up the product step by step.i = 2: the counter starts at 2. Multiplying by 1 does not change the value, so there is no need to start at 1.while i ≤ n: as long as i does not exceed n, the two lines below it are repeated.result = result × i: the product so far is multiplied by i.i = i + 1: the counter increases by one; then control returns to line 5 and the condition is checked again.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.
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.
| State | Condition i ≤ n | Multiply | result | New i |
|---|---|---|---|---|
| start | — | — | 1 | 2 |
| Iteration 1 | 2 ≤ 5 → true | 1 × 2 = 2 | 2 | 3 |
| Iteration 2 | 3 ≤ 5 → true | 2 × 3 = 6 | 6 | 4 |
| Iteration 3 | 4 ≤ 5 → true | 6 × 4 = 24 | 24 | 5 |
| Iteration 4 | 5 ≤ 5 → true | 24 × 5 = 120 | 120 | 6 |
| exit | 6 ≤ 5 → false | — | 120 | 6 |
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.
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.
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.
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| State | Condition i ≤ n | sum | New i |
|---|---|---|---|
| start | — | 0 | 2 |
| Iteration 1 | 2 ≤ 10 → true | 2 | 4 |
| Iteration 2 | 4 ≤ 10 → true | 6 | 6 |
| Iteration 3 | 6 ≤ 10 → true | 12 | 8 |
| Iteration 4 | 8 ≤ 10 → true | 20 | 10 |
| Iteration 5 | 10 ≤ 10 → true | 30 | 12 |
| exit | 12 ≤ 10 → false | 30 | 12 |
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 = nexta 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.
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.
| Round | a printed | next = a + b | New a | New b |
|---|---|---|---|---|
| start | — | — | 0 | 1 |
| 0 | 0 | 0 + 1 = 1 | 1 | 1 |
| 1 | 1 | 1 + 1 = 2 | 1 | 2 |
| 2 | 1 | 1 + 2 = 3 | 2 | 3 |
| 3 | 2 | 2 + 3 = 5 | 3 | 5 |
| 4 | 3 | 3 + 5 = 8 | 5 | 8 |
| 5 | 5 | 5 + 8 = 13 | 8 | 13 |
| 6 | 8 | 8 + 13 = 21 | 13 | 21 |
| 7 | 13 | 13 + 21 = 34 | 21 | 34 |
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.
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.
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 trueThe 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.”
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.
| Comparing | lo | hi | lo < hi | text[lo] | text[hi] | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 4 | 0 < 4 → true | 'k' | 'k' | same, move inward |
| 2 | 1 | 3 | 1 < 3 → true | 'a' | 'a' | same, move inward |
| — | 2 | 2 | 2 < 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.
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.
| Comparing | lo | hi | lo < hi | text[lo] | text[hi] | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 18 | 0 < 18 → true | 'e' | 'e' | same, move inward |
| 2 | 1 | 17 | 1 < 17 → true | 'y' | 'y' | same, move inward |
| 3 | 2 | 16 | 2 < 16 → true | 'e' | 'e' | same, move inward |
| 4 | 3 | 15 | 3 < 15 → true | 'd' | 'd' | same, move inward |
| 5 | 4 | 14 | 4 < 14 → true | 'i' | 'i' | same, move inward |
| 6 | 5 | 13 | 5 < 13 → true | 'p' | 'p' | same, move inward |
| 7 | 6 | 12 | 6 < 12 → true | 'a' | 'a' | same, move inward |
| 8 | 7 | 11 | 7 < 11 → true | 'd' | 'd' | same, move inward |
| 9 | 8 | 10 | 8 < 10 → true | 'a' | 'a' | same, move inward |
| — | 9 | 9 | 9 < 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.
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.
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.
| i | i × i ≤ n | n % i | Decision |
|---|---|---|---|
| 2 | 4 ≤ 29 → true | 29 % 2 = 1 | not a divisor |
| 3 | 9 ≤ 29 → true | 29 % 3 = 2 | not a divisor |
| 4 | 16 ≤ 29 → true | 29 % 4 = 1 | not a divisor |
| 5 | 25 ≤ 29 → true | 29 % 5 = 4 | not a divisor |
| 6 | 36 > 29 → false | — | loop ends → prime |
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.
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.
| i | i × i ≤ n | n % i | Decision |
|---|---|---|---|
| 2 | 4 ≤ 221 → true | 221 % 2 = 1 | not a divisor |
| 3 | 9 ≤ 221 → true | 221 % 3 = 2 | not a divisor |
| 4 | 16 ≤ 221 → true | 221 % 4 = 1 | not a divisor |
| 5 | 25 ≤ 221 → true | 221 % 5 = 1 | not a divisor |
| 6 | 36 ≤ 221 → true | 221 % 6 = 5 | not a divisor |
| 7 | 49 ≤ 221 → true | 221 % 7 = 4 | not a divisor |
| 8 | 64 ≤ 221 → true | 221 % 8 = 5 | not a divisor |
| 9 | 81 ≤ 221 → true | 221 % 9 = 5 | not a divisor |
| 10 | 100 ≤ 221 → true | 221 % 10 = 1 | not a divisor |
| 11 | 121 ≤ 221 → true | 221 % 11 = 1 | not a divisor |
| 12 | 144 ≤ 221 → true | 221 % 12 = 5 | not a divisor |
| 13 | 169 ≤ 221 → true | 221 % 13 = 0 | divisor 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.
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.
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.
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.
| State | i | result | i ≤ n |
|---|---|---|---|
| start | 2 | 1 | — |
| iteration 1 | 2 | 2 | true |
| iteration 2 | 3 | 6 | true |
| iteration 3 | 4 | 24 | true |
| exit | 5 | 24 | 5 ≤ 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.
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.
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.
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.
| Kind | Goal | Input | Expected |
|---|---|---|---|
| Normal | Verify common use | n = 5 | 120 (the loop runs 4 times) |
| Boundary | Try the lower bound | n = 0 | 1 (the loop never runs) |
| Boundary | A second case where the loop never runs | n = 1 | 1 (the loop never runs) |
| Boundary | Try the upper bound | n = 20 | 2,432,902,008,176,640,000 (the loop runs 19 times) |
| Invalid | See the error behavior | n = −3 | “error” |
| Large | See the overflow | n = 21 | 51,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 resultIn 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.
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 + 1The second algorithm (B) uses a formula attributed to Gauss and finds the result in a single step:
sum = n * (n + 1) / 2Where 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.
| n | Result | A: additions in the loop | B: operations in the formula |
|---|---|---|---|
| 10 | 55 | 10 | 1 multiplication, 1 addition, 1 division |
| 100 | 5,050 | 100 | 1 multiplication, 1 addition, 1 division |
| 1,000 | 500,500 | 1,000 | 1 multiplication, 1 addition, 1 division |
| 1,000,000 | 500,000,500,000 | 1,000,000 | 1 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.
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.
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.
| n | Binary search (⌊log₂ n⌋ + 1 iterations) | Linear search (n) | Selection sort (n(n − 1)/2) | n² |
|---|---|---|---|---|
| 10 | 4 | 10 | 45 | 100 |
| 100 | 7 | 100 | 4,950 | 10,000 |
| 1,000 | 10 | 1,000 | 499,500 | 1,000,000 |
| 1,000,000 | 20 | 1,000,000 | 499,999,500,000 | 1,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.
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.
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.
| i | i < arr.length | arr[i] | arr[i] == target | Result |
|---|---|---|---|---|
| 0 | 0 < 5 → true | 7 | 7 == 5 → false | next element |
| 1 | 1 < 5 → true | 3 | 3 == 5 → false | next element |
| 2 | 2 < 5 → true | 9 | 9 == 5 → false | next element |
| 3 | 3 < 5 → true | 5 | 5 == 5 → true | return 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).
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.
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:
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.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.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.if (arr[mid] == target) return mid;: if the middle element is the target, the search ends.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.else hi = mid - 1;: otherwise the middle element is greater than the target; the right half is eliminated together with the middle.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.
| Round | lo | hi | mid | arr[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 0 + (8 − 0) / 2 = 4 | 21 | 21 < 34 → lo = 5 |
| 2 | 5 | 8 | 5 + (8 − 5) / 2 = 6 | 30 | 30 < 34 → lo = 7 |
| 3 | 7 | 8 | 7 + (8 − 7) / 2 = 7 | 34 | 34 == 34 → return 7 |
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.
| Round | lo | hi | mid | arr[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 0 + (7 − 0) / 2 = 3 | 17 | 17 < 19 → lo = 4 |
| 2 | 4 | 7 | 4 + (7 − 4) / 2 = 5 | 25 | 25 > 19 → hi = 4 |
| 3 | 4 | 4 | 4 + (4 − 4) / 2 = 4 | 21 | 21 > 19 → hi = 3 |
| — | 4 | 3 | — | — | 4 ≤ 3 → false: the range is empty, return −1 |
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.
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).
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.
| Property | Linear search | Binary search |
|---|---|---|
| Sorted data | Not required | Required |
| Best case | 1 comparison (target is the first element) | 1 iteration (target is in the middle) |
| Worst-case time | O(n) | O(log n) |
| Extra memory | O(1) | O(1) |
| Structure | An array, or a data stream read from start to end | A sorted structure with random access |
| Suitable use | Little or unsorted data, a single search | Many 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.
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.
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.
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.
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.
The example array here is {29, 10, 14, 37, 13}. The result of each pass is given in Table 4.1.14.
| Pass | Unsorted part | Comparing | New values of minIdx | Swap | Array at end of pass |
|---|---|---|---|---|---|
| i = 0 | 0…4 | 4 | 10 (arr[1]) | arr[0] ↔ arr[1] | [10, 29, 14, 37, 13] |
| i = 1 | 1…4 | 3 | 14 (arr[2]), 13 (arr[4]) | arr[1] ↔ arr[4] | [10, 13, 14, 37, 29] |
| i = 2 | 2…4 | 2 | unchanged | in place (no effect) | [10, 13, 14, 37, 29] |
| i = 3 | 3…4 | 1 | 29 (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.
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).
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.
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 falseAt 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.
| Pass | j | Pairs compared (↔ swap) | Comparing | Array at end of pass | swapped |
|---|---|---|---|---|---|
| Pass 1 | 0…3 | (5, 1)↔ (5, 4)↔ (5, 2)↔ (5, 8) | 4 | [1, 4, 2, 5, 8] | true |
| Pass 2 | 0…2 | (1, 4) (4, 2)↔ (4, 5) | 3 | [1, 2, 4, 5, 8] | true |
| Pass 3 | 0…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.
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).
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.
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] = keyThe 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.
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.
| Step | key | Comparisons | Key | Shifts | Index where placed | Array after |
|---|---|---|---|---|---|---|
| i = 1 | 3 | 4 > 3 ✓ (j = −1, stops) | 1 | 1 | 0 | [3, 4, 5, 1] |
| i = 2 | 5 | 4 > 5 ✗ | 1 | 0 | 2 | [3, 4, 5, 1] |
| i = 3 | 1 | 5 > 1 ✓, 4 > 1 ✓, 3 > 1 ✓ (j = −1, stops) | 3 | 3 | 0 | [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.
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.
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.
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 merged | Result | Comparing |
|---|---|---|
| [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 |
| Total | 17 |
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
| Algorithm | Basic idea | Worst case | Best case | Extra space |
|---|---|---|---|---|
| Selection | Select the smallest and place it | O(n²) | O(n²) | O(1) |
| Bubble | Swap neighbors | O(n²) | O(n) (with early stopping) | O(1) |
| Insertion | Insert the element into the sorted part | O(n²) | O(n) | O(1) |
| Merge | Split, sort, merge | O(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.
| Input (n = 5) | Selection | Bubble (with early stopping) | Insertion |
|---|---|---|---|
| Sorted [1, 2, 3, 4, 5] | 10 / 0 | 4 / 0 | 4 / 0 |
| Reverse sorted [5, 4, 3, 2, 1] | 10 / 2 | 10 / 10 | 10 / 10 |
| Shuffled [5, 1, 4, 2, 8] | 10 / 2 | 9 / 4 | 7 / 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.
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
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.
In the algorithm that sums the even numbers,
i = 1was mistakenly written instead ofi = 2; the increment is stilli = 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.
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.
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.
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.
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.
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.
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).
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
- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022.
- A. Levitin, Introduction to the Design and Analysis of Algorithms, 3rd ed., Pearson, 2012.
- R. Sedgewick, K. Wayne, Algorithms, 4th ed., Addison-Wesley, 2011. Book site.
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 4.1 Performance, 4.2 Sorting and Searching.
- 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.