Object-Oriented Programming with Java · Lecture Notes

Chapter 1.3: Algorithms

Writing a program does not begin at the keyboard. First it becomes clear what the problem asks, then the solution is put on paper step by step, and only at the end are these steps translated into a programming language. These notes walk through every stop on this road with small but complete examples. The first sections cover defining a problem by its input, output and test cases; writing the solution in pseudocode and tracing it by hand with a variable table; and translating pseudocode into Java. Then come the algorithms for sorting two and three numbers, factorial, Fibonacci, exponentiation, palindromes and primes. Each is treated in the same pattern: problem definition, pseudocode, hand trace, Java code and tests. The notes end with the three simple methods of searching and sorting: random, linear and binary search; shuffling, selection sort and bubble sort. In every section, Java-specific pitfalls are given together with the real messages of the compiler and the runtime.

Learning outcomes

Problem solving
Define a problem by its input, output and test cases; think about edge cases separately; write the solution first as an algorithm, then as code.
Pseudocode and tracing
Express an algorithm in pseudocode and trace it by hand, step by step, with a variable table.
Translating to Java
Translate reading, writing, decision and loop steps into their Java counterparts; use details such as Scanner, print/println, integer division, long and equals correctly.
Basic algorithms
Write, trace and test the algorithms for ordered printing, factorial, Fibonacci, palindromes, primes and exponentiation.
Searching
Compare random, linear and binary search; explain why binary search needs sorted data; compute the worst-case number of comparisons.
Sorting
Apply shuffling, selection sort and bubble sort step by step on an array; find the numbers of comparisons and swaps.

1.3.1Problem solving

Someone new to programming often starts writing code the moment they read the problem. For small problems this works for a while. Once the problem grows a little, the code turns into a heap of patches whose purpose is unclear. When an error appears, its source cannot be found either, because nothing written down says "what the program is supposed to do". Experienced programmers therefore split the work into stages. The output of each stage is the input of the next, and each stage can be checked on its own.

1.3.1.1Algorithm first, implementation second

Solving a problem with a computer is a cycle of four steps (Figure 1.3.1). The first step is defining the problem: what will be given and what is wanted? As long as the answer to this question stays vague, all the later steps can go to waste. The second step is determining the algorithm. An algorithm is the list of steps to follow to solve the problem. There may be more than one algorithm for the same problem; the right choice determines the speed and memory use of the program. The third step is translating the algorithm into code in the chosen programming language, in this course Java. In the fourth step the program is tried against test cases prepared beforehand. If a test does not give the expected result, we return to the earlier steps. The mistake may be in the coding, in the algorithm, or even in a misunderstanding of the problem.

1Definethe problem2Determinethe algorithm3Translateinto code4Test,verifyif a bug is found, go back and fix it
Figure 1.3.1: The problem-solving cycle. If a test shows an error, we go back along the dashed arrow and fix the step that was the source of the error.

The most important gain of this arrangement is that mistakes are caught while they are cheap. A mistake found in an algorithm on paper is fixed with a few lines. If the same mistake is found after it has been buried in a program of hundreds of lines, both finding and fixing it cost far more. Preparing the test cases before writing the code rests on the same reason. Tests prepared after the program is written tend, without our noticing, to treat what the program does as "correct".

1.3.1.2What is an algorithm?

Definition 1.3.1

An algorithm is a sequence of instructions for solving a problem, made of clear steps in a definite order and finite in number.

The word comes from the name of the mathematician al-Khwarizmi, who lived in 9th-century Baghdad. The Latin spelling of his name was Algoritmi; the Latin translation of his book on calculating with decimal numbers became known in Europe under this name. Over time the word "algorithm" came to be used for any step-by-step described method of calculation.

A computer does not understand an algorithm directly. An algorithm is written in the way people think; a computer only runs commands in its own machine language. The bridge between them is the programming language: the algorithm is translated into a language such as Java, and the compiler turns this text into a form the machine can run. Just as an algorithm can be written as several programs, a problem can have several algorithms. These algorithms are usually compared by two measures: how long they take to finish and how much memory they use.

The most familiar everyday analogy is a cooking recipe. The ingredients are the input, the steps of preparation are the algorithm, and the resulting dish is the output. But recipes are written for people and contain vague steps such as "add a little salt" or "stir until it thickens". An experienced cook fills these gaps with their own knowledge. A computer cannot attach a number to the word "little"; it must be told "add 5 grams of salt". For a list of instructions to count as an algorithm, it is expected to have five properties (Table 1.3.1).

Table 1.3.1: The five properties of an algorithm and their counterparts in a recipe.
PropertyMeaningWhere the recipe breaks it
InputTakes zero or more initial data items.—
OutputProduces at least one result.—
DefinitenessEach step is clear and has a single meaning."Add a little salt."
FinitenessEnds after a finite number of steps."Stir until it looks done."
EffectivenessEach step can really be carried out."Chop infinitely fine."

Defining the input property as "zero or more" is deliberate. An algorithm that prints the first ten primes on the screen has no input at all, but it is still an algorithm. A method with no output, on the other hand, produces nothing and is useless; that is why at least one output is required. Finiteness means that the algorithm stops at some point for every input. A loop that runs forever when the user enters a wrong value breaks this property. Effectiveness requires the steps to be actually doable: the step "list all the primes" is clear and single-meaning, but cannot be done because there are infinitely many primes.

1.3.1.3Defining the problem and test cases

Defining the problem means writing down the program's inputs and outputs explicitly in natural language. The sentence "add two numbers" looks sufficient at first glance. A little thought raises questions: are the numbers integers, or can they be decimals too? Can a negative number be entered? Will the result be written to the screen or used in another computation? As the answers to these questions are added to the definition, what the program will do becomes clear.

The second part of the definition is the test cases. A test case is writing down in advance the expected output for a given input. The program is run and the output it produces is compared with the expected one; if the two are the same the test passes (Figure 1.3.2). The expected output must be found independently of the program, by hand or in another reliable way. Otherwise the test amounts to nothing more than comparing the program with itself.

input3, 5programoutput8=expected: 8test passed
Figure 1.3.2: How a test works: the input 3 and 5 is given to the program, the 8 it produces is compared with the expected 8, and the test passes.

Table 1.3.2 shows test cases prepared for two small problems. In each problem the first two rows are ordinary inputs. The third rows are deliberately chosen edge cases. Zero, an empty string, a negative number, the first or last element of an array are extreme inputs of this kind. Programmers naturally think of ordinary inputs; extremes are easily forgotten. That is why bugs hide most often at the extremes. A program that counts words may give 2 for "Hello, world!" yet give 1 for an empty string. A simple approach that splits the text at spaces counts even an empty string, which contains no spaces, as one piece.

Table 1.3.2: Test cases for two problems. The third rows are edge cases.
ProblemTestInputExpected output
Sum of two numbers13, 58
2−2, 75
3 (edge)0, 00
Number of words in a text1"Hello, world!"2
2"A short test."3
3 (edge)"" (empty string)0

A good test set covers few but mutually different cases. For addition, the tests 3 + 5, 4 + 6 and 10 + 20 test the same thing three times: all three are positive integers. Choosing instead a positive pair, a pair with a negative and a pair with a zero gives much more chance of catching errors for the same effort. In all the algorithms in these notes the test cases are chosen with this principle: each has both ordinary and extreme inputs.

1.3.1.4Determining the algorithm and tracing by hand

Once the problem is defined, the steps of the solution are written in order. For the sum of two numbers, the algorithm has four steps:

  1. Get the first number.
  2. Get the second number.
  3. Add the two numbers.
  4. Print the sum on the screen.

The job is not done once the algorithm is written; before any code is written, the algorithm itself is tested. The way to do this is the dry run. A test case is chosen and the algorithm is run on paper step by step. After each step the values of the variables are written into a table. This table is called a trace table. The columns of the table are the variables and the screen, and the rows are the steps. If a cell is left empty, that variable has not yet received a value at that moment.

Table 1.3.3: Dry run of the addition algorithm for test 1 (input 3, 5). 8 was printed on the screen; the expected value was also 8.
Stepnum1num2sumScreen
1. Get the first number3
2. Get the second number35
3. Add the two numbers358
4. Print the sum3588

In this example the trace is very easy and may seem unnecessary. But the same habit makes a big difference with loop algorithms. How many times a loop runs, what value a variable takes in which iteration, whether the loop ends one iteration too early or too late: these can be seen reliably only with a table like this. For hand tracing, small but meaningful test cases are chosen. For factorial, 5 is a good choice: five iterations can be traced by hand and the result (120) is known by heart. 20 is a bad choice; both the table grows long and verifying the result becomes difficult.

1.3.1.5Pseudocode

An algorithm can be written in four forms: in natural language, in pseudocode, as a flowchart, or directly in a programming language. Natural language is a tool everyone understands but is open to ambiguity. A programming language is exact but its burden of detail is heavy: semicolons, type declarations and library names overshadow the real idea. Pseudocode stands between the two.

Definition 1.3.2

Pseudocode is a notation for algorithms, written for people, that resembles a programming language but has no compiler rules. It uses fixed keywords for basic structures such as reading, writing, assignment, decisions and loops; everything else can be written in natural language.

Pseudocode has two big benefits. First, it makes it easier to find logic errors before writing code: attention goes not to syntax but to the order of the steps and the conditions. Second, it lets programmers who use different languages talk about the same algorithm. Someone who knows Java and someone who knows Python can read the same pseudocode and translate it into their own languages. The pseudocode keywords used in these notes and their Java counterparts are collected in Table 1.3.4.

Table 1.3.4: Pseudocode keywords and their Java counterparts.
PseudocodeMeaningJava counterpart
Start … EndBeginning and end of the algorithmThe { … } body of the main method
Read xGet a value from the userx = scanner.nextInt();
Print "…", xDisplay on the screenSystem.out.println("…" + x);
x = 5Assign a value to a variablex = 5;
If x = y thenCompare for equalityif (x == y) (two equals signs)
ElseIf the condition is falseelse
For i = 1 to nRepeatfor (int i = 1; i <= n; i++)
BreakLeave the loop at oncebreak;
%, and, orRemainder, logical and/or%, &&, ||

The trickiest row of the table is the equality row. In pseudocode and in mathematics the = sign is used both for assignment and for comparison; the meaning is inferred from context. In Java these two jobs are done with different signs. A single equals sign (=) puts the value on the right into the variable on the left. A double equals sign (==) compares two values and produces true or false. When translating pseudocode into Java, the sign in every If … = … then line must be turned into ==.

Common mistake

Using a single equals sign in a condition. The line if (num % divisor = 0) does not compile. Since the left side is a computed value and not a variable, the compiler gives this message: error: unexpected type … required: variable, found: value. If the left side were a variable, for example if (s = 5), the message would change: error: incompatible types: int cannot be converted to boolean. Since if accepts only boolean in Java, this mistake is caught at compile time. In languages like C the same line compiles silently and corrupts the logic of the program.

A similar distinction exists for logical operators. The "and" of pseudocode is written && in Java and "or" is written ||. These operators short-circuit. In a && b, if a is false the result is false anyway, so b is never evaluated. In a || b, if a is true, b is not looked at.

1.3.2Translating to code

After the algorithm is prepared and traced by hand, the next step is coding (implementation). The programming language expresses the algorithm in a form the computer can compile and run. When writing code, the program is divided into logical parts: taking input, computing and giving output. In larger programs each part moves into a separate method. Each line of pseudocode usually corresponds to one or a few lines of Java.

1.3.2.1From pseudocode to a running program

There are four stops before an algorithm produces a result on screen (Figure 1.3.3). The pseudocode is translated into Java source code and written to a file such as Addition.java. The Java compiler javac reads this file. If there is no typing error in the code, it produces a bytecode file named Addition.class. Bytecode is not the machine language of a particular processor. It is an intermediate language understood by the Java Virtual Machine (JVM). The command java Addition starts the JVM; the JVM runs the bytecode and the output appears on screen. The same .class file runs on Windows, on Linux or on macOS, on any machine with a JVM installed.

PseudocodealgorithmAddition.javasource codeAddition.classbytecodeOutputJVM runs itcodingjavacjava
Figure 1.3.3: From pseudocode to output: coding, compiling with javac, and running on the JVM with the java command.

Errors can show up at two different moments. Compile errors are found while javac runs: a missing semicolon, a misspelled keyword, an undeclared variable, an incompatible type. No .class file is produced from a program with a compile error. Runtime errors, on the other hand, appear while the program runs: accessing a nonexistent cell of an array, dividing by zero, the user typing a letter instead of a number. The third and most dangerous kind is logic errors. The program compiles, runs, gives no message, but produces a wrong result. Only tests catch such errors.

The correspondence between the algorithm steps and the Java lines is seen in Table 1.3.5. Each step has become a single line. In more complex algorithms a step may take several lines; but the correspondence must always remain traceable.

Table 1.3.5: The steps of the addition algorithm and their Java counterparts.
Algorithm stepJava
Get the first numbernum1 = scanner.nextDouble();
Get the second numbernum2 = scanner.nextDouble();
Add the two numberssum = num1 + num2;
Print the sumSystem.out.println(sum);

A note on naming: the Java libraries use English names (Scanner, nextDouble, println), and in this course we choose our own variable and method names in English too, and keep them to plain ASCII letters. Java does accept names with letters from other alphabets, such as the Turkish ş or ı. Still, when a source file is opened with a different character encoding, such letters can get garbled and lead to a compile error. Pseudocode has no such problem; there, names like firstInteger can be used freely.

1.3.2.2The addition program

The complete Java program for the addition algorithm is below. Code that the slides show only as the body of main is given here together with the import line and the class definition; in this form it can be written to a file named Addition.java and compiled.

import java.util.Scanner;

public class Addition {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();
        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();
        double sum = num1 + num2;
        System.out.println(num1 + " + " + num2
                + " = " + sum);
        scanner.close();
    }
}

The import java.util.Scanner; on the first line tells the compiler where to find the Scanner class. Java's standard library is divided into packages, and Scanner is in the java.util package. A few basic classes such as System and String are in the java.lang package, which is added to every program automatically. Every other class needs an import. If the line is forgotten, the compiler does not recognize the name Scanner:

Addition.java:4: error: cannot find symbol
        Scanner scanner = new Scanner(System.in);
        ^
  symbol:   class Scanner
  location: class Addition

Since Scanner appears twice on the same line, the compiler reports this error twice and says "2 errors". A single missing line can cause several error messages. This is why compile errors are always read starting from the first one.

The line public class Addition defines the class. The name of a public class must be the same as the file name: the Addition class sits in the file Addition.java. public static void main(String[] args) is the starting point of the program; the JVM begins running from this method. The counterpart of the Start … End pair in the pseudocode is the curly braces of this method.

Scanner scanner = new Scanner(System.in); creates an object that will read from the keyboard. System.in is the standard input stream, that is, the keyboard. The nextDouble() method of the scanner object reads the next number as a double, nextInt() as an int, and nextLine() reads the whole line as text. The scanner.close(); at the end of the program releases the resource the object uses.

In the line double sum = num1 + num2;, the right side is computed first and then the result is put into the variable on the left. Assignment always works from right to left. That is why a line like total = total + 1, which looks absurd in mathematics, makes sense in programming: "add 1 to the current value of total and put the result back into total".

1.3.2.3Tracing the addition program

The line-by-line trace of a run in which the user enters 3 and 5 is in Table 1.3.6. The line numbers are the lines of the main body: line 1 is where the Scanner is created, and line 9 is the close call.

Table 1.3.6: Trace of the addition program (input 3 and 5). The "Screen" column is the text accumulated on screen after that line; ↵ is the end of a line.
Linenum1num2sumScreenExplanation
1———A Scanner is created to read from the keyboard.
2———Enter the first number:print does not move to the next line; the cursor waits next to the message.
33.0——… number: 3↵The user types 3 and presses Enter; nextDouble() reads 3.0.
43.0——Enter the second number:The second message is printed.
53.05.0—… number: 5↵The user enters 5.
63.05.08.0The right side is computed: 3.0 + 5.0 = 8.0.
7–83.05.08.03.0 + 5.0 = 8.0↵+ concatenates the strings.
93.05.08.0The scanner is closed and the program ends.

The last line the program writes to the screen is "3.0 + 5.0 = 8.0". The test case expected 8; the program printed 8.0. The value is the same; the form of writing differs. When a number of type double is converted to text, it is written with its decimal part, as "8.0", even if it is a whole number. Such format differences must also be considered when writing test cases. A program that does the testing automatically counts the texts "8" and "8.0" as different.

double num13.0double num25.0double sum8.0
Figure 1.3.4: The three double variables in memory just before the program ends.

1.3.2.4Details of reading and writing

print and println. Both methods write the value given to them on the screen. The difference is in what happens afterwards. println (print line) writes the value and moves to the next line; print does not. This is why print is used when asking the user for input: the cursor waits right next to the message "Enter the first number: " and the user types the number on the same line. print is also used to write a series of values side by side on one line; after the last value a println() completes the line.

String concatenation and order of evaluation. The + operator adds between two numbers and concatenates between a string and any value. An expression is evaluated from left to right, and this can lead to surprising results. Table 1.3.7 shows outputs obtained by running on JDK 21.

Table 1.3.7: Behavior of the + operator with numbers and strings; division and remainder.
ExpressionOutputReason
3 + 5 + " total"8 totalFirst 3 + 5 = 8 is added, then it is appended to the string.
"total " + 3 + 5total 35String + 3 = "total 3"; then + 5 is concatenation again.
"total " + (3 + 5)total 8The parentheses bring the addition forward.
7 / 23Integer division between two ints; the fraction is discarded.
7 % 21Remainder.
-7 / 2 and -7 % 2−3 and −1The quotient is truncated toward zero; the remainder takes the sign of the dividend.
7.0 / 23.5If one of the operands is a double, true division is performed.

Integer division is used often in the algorithms of this chapter. The num / 2 in the prime check and the (low + high) / 2 in binary search are both integer division and discard the fractional part on purpose. The remainder operator % is at least as important. num % divisor == 0 means "divides exactly"; num % 10 gives the last digit, and num % 2 tells whether a number is even or odd.

Decimal separator and locale. When reading numbers, Scanner uses the computer's locale. On a computer set to Turkish, the decimal separator is the comma. So typing "3,5" into the addition program works, while typing "3.5" stops the program:

Enter the first number: 3.5
Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:947)
	at java.base/java.util.Scanner.next(Scanner.java:1602)
	at java.base/java.util.Scanner.nextDouble(Scanner.java:2573)
	at Addition.main(Addition.java:7)

On a computer set to English the situation is the reverse: "3.5" is accepted and "3,5" is rejected. The output of the program, however, is in the form "3.5" in both settings, because converting a double value to text does not look at the locale. The same program behaving differently on different computers often surprises students. If you want reading to be the same everywhere, create the scanner as new Scanner(System.in).useLocale(Locale.US). When the user types a letter instead of a number, the same InputMismatchException is thrown. Catching this exception and asking the user again is a more advanced topic. The programs in these notes assume that the user enters a valid number.

1.3.3Algorithms with decision structures

From this section on, every algorithm is treated in the same pattern. First the problem and test cases are defined, then pseudocode is written and traced by hand with a variable table. Finally the Java code is given and the tests are run. The first two examples contain no loops. The path the algorithm follows depends on decisions made by comparing the inputs.

1.3.3.1Printing two integers in order

Problem definition. The input is two integers. The output is the same two numbers, with the smaller one written first. The test cases are in Table 1.3.8. The third test is an edge case: the two numbers are equal.

Table 1.3.8: Test cases for printing two integers in order.
InputExpectedCase tested
4, 114 11Numbers already in order
13, 1111 13Numbers in reverse order
7, 77 7Equal numbers (edge)

Pseudocode. The algorithm reads two numbers and makes a single comparison. If the first number is smaller than the second, the numbers are printed in the order they were read; otherwise in the reverse order.

Start
    Print "Enter the first integer: "
    Read firstNum
    Print "Enter the second integer: "
    Read secondNum
    If firstNum < secondNum then
        Print firstNum, " ", secondNum
    Else
        Print secondNum, " ", firstNum
    End If
End

The If … then … Else … End If structure splits the algorithm into two branches. If the condition is true only the first branch runs, if false only the second; the two branches never run together. After the End If line the two paths merge again.

Hand trace. Table 1.3.9 is the trace of the first two tests. For the input (4, 11) the condition is true and the then branch runs. For the input (13, 11) the condition is false; the Else branch first writes the second number, that is, the smaller one.

Table 1.3.9: Hand trace of the two-integer algorithm for (4, 11) and (13, 11).
TestStepfirstNumsecondNumConditionScreen
1Read firstNum4
Read secondNum411
If 4 < 11411true
then branch4114 11
2Read firstNum13
Read secondNum1311
If 13 < 111311false
Else branch131111 13

The equal-numbers test can be settled even without tracing. For (7, 7) the condition 7 < 7 is false and the Else branch runs. This branch writes "second, then first"; since the two numbers are the same, the output is again "7 7". Had ≤ been used in the condition instead of <, the then branch would have run for equal numbers and the result would not change. The edge-case test catches no bug here but guarantees that the algorithm is correct for equal numbers too.

Java code. The Java counterpart of the pseudocode is below. Each Print became a System.out.print or println, and each Read a nextInt().

import java.util.Scanner;

public class SortTwo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first integer: ");
        int first = scanner.nextInt();
        System.out.print("Enter the second integer: ");
        int second = scanner.nextInt();
        if (first < second) {
            System.out.println(first + " " + second);
        } else {
            System.out.println(second + " " + first);
        }
        scanner.close();
    }
}

When the program is compiled with JDK 21 and run with the three tests, it prints "4 11", "11 13" and "7 7" in turn; all three tests pass. At the start of the output the messages "Enter the first integer: Enter the second integer: " also appear. When the user types the numbers in a terminal, these messages fall on separate lines because the user presses Enter after each number.

In Java each branch of if and else is either a single statement or a block wrapped in curly braces. In the code above, even the one-line branches are put in braces. This is not a requirement but a good habit. If a second line is later added to a brace-less branch, that line always runs regardless of the condition, and its indentation hides this.

1.3.3.2Printing three integers in order

Problem definition. The input is three integers; the output is the same numbers written from smallest to largest. This problem makes you think about choosing test cases. Three numbers can arrive in 3! = 6 different orders: 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2 and 3 2 1. Each order passes through a different path of the algorithm; if all six orders are tried, every branch of the algorithm will have run at least once. Inputs with equal numbers are added to these: for 5 5 2 the expected output is 2 5 5.

Idea. First the smallest of the three numbers is found and written. The remaining two numbers are sorted and written with the two-integer algorithm. Since the smallest number can be the first, second or third, the algorithm has three main branches. Within each main branch there is also a small two-number decision.

Start
    // Get the first integer
    Print "Enter the first integer: "
    Read firstNum
    // Get the second integer
    Print "Enter the second integer: "
    Read secondNum
    // Get the third integer
    Print "Enter the third integer: "
    Read thirdNum
    // Print in ascending order
    If firstNum ≤ secondNum and
         firstNum ≤ thirdNum then
        Print firstNum
        If secondNum ≤ thirdNum then
            Print secondNum, " ", thirdNum
        Else
            Print thirdNum, " ", secondNum
        End If
    Else If secondNum ≤ firstNum and
         secondNum ≤ thirdNum then
        Print secondNum
        If firstNum ≤ thirdNum then
            Print firstNum, " ", thirdNum
        Else
            Print thirdNum, " ", firstNum
        End If
    Else
        Print thirdNum
        If firstNum ≤ secondNum then
            Print firstNum, " ", secondNum
        Else
            Print secondNum, " ", firstNum
        End If
    End If
End

The first condition asks whether the first number is less than or equal to both of the others. The two comparisons are joined with "and": both must be true. If this branch runs, the first number is printed, and the remaining second and third numbers are ordered with a nested decision. If the first condition is false, we check whether the second number is the smallest. If that is false too, the smallest number is the third and the last branch runs. No separate condition is needed in the last branch: once the first two are ruled out, only one possibility is left.

Using ≤ rather than < in the comparisons is necessary for equal numbers. Suppose the conditions were written with strict < and the input were 5 5 7. For the first number, 5 < 5 is false; for the second number, 5 < 5 is false too. The algorithm falls into the last branch, writes 7 first as the "smallest" number, and the output is "7 5 5". When the smallest value occurs in two numbers at once, no number is "strictly smaller than the others". ≤, on the other hand, directly expresses "the smallest or one of the smallest", and for this input it runs the first branch. The test 5 5 2 does not catch this bug, because there the smallest number is unique. Only a test like 5 5 7, where the smallest value is repeated, exposes it.

An observation is hidden in the pseudocode. The same job of "sort two numbers and print them" is repeated in three places, with only the variable names changed. A repeated job is a very good candidate for turning into a function (a method in Java). If a method like printTwo(int a, int b) is written, each of the three branches shrinks to a single line. Methods are a separate topic; what matters here is the habit of noticing repetition.

1.3.3.3Java code and trace for three integers

The full Java program from the slides is below. The three main branches of the pseudocode have become an if … else if … else chain, and the inner decisions one-line if … else statements. The "and" has become &&.

import java.util.Scanner;

public class SortThree {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter three integers: ");
        int first = scanner.nextInt();
        int second = scanner.nextInt();
        int third = scanner.nextInt();
        if (first <= second && first <= third) {
            System.out.print(first + " ");
            if (second <= third) System.out.println(second + " " + third);
            else                  System.out.println(third + " " + second);
        } else if (second <= first && second <= third) {
            System.out.print(second + " ");
            if (first <= third) System.out.println(first + " " + third);
            else                   System.out.println(third + " " + first);
        } else {
            System.out.print(third + " ");
            if (first <= second) System.out.println(first + " " + second);
            else                   System.out.println(second + " " + first);
        }
        scanner.close();
    }
}

There is one more detail in this program. System.out.print("Enter three integers: ") writes a single message and the three nextInt() calls follow one after another. Scanner reads numbers as pieces separated by spaces or line ends. The user can type "7 3 5" and press Enter once, or press Enter after each number; in both cases the three numbers are read correctly.

Code trace. Let the input be 7, 3, 5. Table 1.3.10 gives the value of each condition and what is printed, step by step.

Table 1.3.10: Trace of the SortThree program for (7, 3, 5). first = 7, second = 3, third = 5.
StepExpression examinedValueScreen
1first <= second → 7 ≤ 3false; the right side of && is not looked at
2second <= first && second <= third → 3 ≤ 7 and 3 ≤ 5true; the smallest is the second
3System.out.print(second + " ")—3
4second <= third → 7 ≤ 5false3
5else branch: println(third + " " + first)—3 5 7

Short-circuit behavior shows in the first step. As soon as first <= second turns out false, it is certain that the whole && expression will be false; Java never makes the comparison first <= third. In this example the skipped comparison is harmless. But when the right side is a method call or an expression that risks division by zero, short-circuiting is used on purpose. The expression b != 0 && a / b > 2 never attempts the division when b is zero.

first7second3third5order: 3 5 7
Figure 1.3.5: The three variables at the end of the trace and the order produced: 3 5 7.

Tests. The program prints "1 2 3" for each of the six orders. For 5 5 2 it prints "2 5 5" and for 7 3 5 it prints "3 5 7". These results were obtained by running the program itself on JDK 21. The inputs 5 2 5, 2 5 5, 5 5 7 and 4 4 4 were also tried, and the right order was found in all. When the same program was rewritten with strict < and tried, it printed "7 5 5" for 5 5 7.

Common mistake

Trying to solve the three-number problem by writing out all the possibilities one by one. A separate condition can be written for each of the six orders: if (a < b && b < c) … else if (a < c && c < b) …. The result is a six-branch structure that is hard to read. For equal numbers, some of the conditions may enter no branch and the program ends without printing anything. The idea "first find the smallest, then sort the rest" breaks the problem into small parts and makes it possible to verify each part separately.

1.3.4Algorithms with loops

Decision structures determine which path the algorithm takes. Loops make a job repeat. The factorial, Fibonacci and exponentiation algorithms in this section rest on the same basic pattern. One or two variables get an initial value before the loop. In each iteration of the loop these variables are updated. When the loop ends, the result is in these variables. The details of the pattern vary from algorithm to algorithm, and mistakes occur precisely in those details.

1.3.4.1Factorial

Definition 1.3.3

The factorial of a non-negative integer n is the product of all the integers from 1 to n: n! = 1 × 2 × 3 × … × n. Also, 0! = 1 by convention.

The rule 0! = 1 may look arbitrary. But when no numbers are multiplied, what remains is 1, the identity of multiplication, just as the result is 0 when no numbers are added. The factorial gives the number of different orders in which n distinct objects can be arranged. That is why 3! = 6 orders were tried in the three-number sorting problem. Table 1.3.11 gives the test cases.

Table 1.3.11: Test cases for factorial. 0 and 1 are edge cases.
nn!
01
11
36
5120
103.628.800

Pseudocode.

Start
    // Enter a number
    Read num
    // Initialize the result
    factorial = 1
    // Loop to compute the factorial
    For i = 1 to num
        factorial = factorial * i
    End For
    Print "Factorial of the number: ", factorial
End

The factorial variable is an accumulator. In each iteration of the loop, a piece of the result is added onto it; here "adding" means multiplying. The accumulator's initial value is the identity of the operation being done: 1 for multiplication, 0 for addition. If the accumulator were initialized to 0, every product would be 0 and the result would always come out 0.

Hand trace. The trace for num = 5 is in Table 1.3.12. The loop variable i starts at 1 and increases by one each iteration. When i becomes 6, the condition 6 ≤ 5 is false and the loop ends.

Table 1.3.12: Trace of the factorial algorithm for num = 5.
Iterationii ≤ 5Operationfactorial
start——factorial = 11
11true1 × 11
22true1 × 22
33true2 × 36
44true6 × 424
55true24 × 5120
exit6falsethe loop ends; 120 is printed120
12345××××factorial = 1 × 2 × 3 × 4 × 5 = 120
Figure 1.3.6: When the loop ends, all five factors have been used: 1 × 2 × 3 × 4 × 5 = 120.

In the edge case num = 0, the loop condition is false on the first try (1 ≤ 0); the body never runs and the accumulator's initial value 1 is printed. This agrees with the rule 0! = 1. The algorithm needs no separate branch for 0; the right initial value solves the edge case by itself.

Java code.

import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        long factorial = 1;
        for (int i = 1; i <= num; i++) {
            factorial = factorial * i;
        }
        System.out.println("Factorial of the number: " + factorial);
        scanner.close();
    }
}

The line For i = 1 to num in the pseudocode has become for (int i = 1; i <= num; i++) in Java. The for header has three parts: the initialization (int i = 1), the continuation condition (i <= num) and the update done at the end of each iteration (i++). The "to num" in the pseudocode includes the number itself; that is why the condition is written with <=, not <.

Why long? The factorial grows very fast. In Java, int is a 32-bit integer and holds at most 2,147,483,647. 12! = 479,001,600 is below this limit; 13! = 6,227,020,800 is above it. Had the accumulator been declared int, the program would print 1,932,053,504 for 13 without any error message. This number is obtained by subtracting 232 = 4,294,967,296 from 6,227,020,800: when the int limit is exceeded, the number wraps around. This event is called overflow. Java does not check for overflow and throws no exception. long is 64 bits and holds at most 9,223,372,036,854,775,807; 20! = 2,432,902,008,176,640,000 fits in it. For 21!, long overflows too and the program prints a meaningless negative number such as −4,249,290,049,419,214,848. For larger factorials the java.math.BigInteger class is used.

Common mistake

Initializing the accumulator inside the loop. If the line long factorial = 1; is written inside the for body, the variable becomes 1 again in every iteration. After the loop the variable cannot even be reached, because a variable declared in the body is valid only in that body. The compiler reports a cannot find symbol error at the System.out.println line. The accumulator is always declared before the loop, outside it.

1.3.4.2The Fibonacci sequence

Definition 1.3.4

The first two terms of the Fibonacci sequence are 0 and 1; every later term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

The problem is to print as many terms as the number n that the user enters. The test cases are in Table 1.3.13. n = 1 and n = 2 are edge cases: in these cases the loop should not run at all, and only the first terms should be printed.

Table 1.3.13: Test cases for Fibonacci.
n (number of terms)Expected output
10
20 1
50 1 1 2 3
70 1 1 2 3 5 8
Start
    // Enter how many terms are wanted
    Read n
    // Initialize the first two Fibonacci numbers
    a = 0
    b = 1
    If n ≥ 1 then Print a
    If n ≥ 2 then Print b
    // Compute the remaining terms
    For i = 2 to n − 1
        result = a + b
        a = b
        b = result
        Print result
    End For
End

The algorithm does not store the whole sequence; it keeps only the last two terms. a is the one before last, b is the last term. The new term is computed with result = a + b. Then two assignments shift the values by one step: a = b makes the old last term the "previous", and b = result makes the new term the "last". The first two terms are written before the loop, after checking whether n is large enough. The loop runs from i = 2 to n − 1, that is, n − 2 iterations. Since each iteration prints one term, the total number of terms is 2 + (n − 2) = n.

Hand trace. The trace for n = 5 is given line by line in Table 1.3.14.

Table 1.3.14: Trace of the Fibonacci algorithm for n = 5.
StageiresultabScreen
start——01
5 ≥ 1, 5 ≥ 2——010 1
iteration 120 + 1 = 1110 1 1
iteration 231 + 1 = 2120 1 1 2
iteration 341 + 2 = 3230 1 1 2 3
exit55 ≤ 4 false; the loop ends0 1 1 2 3
01122334ab
Figure 1.3.7: The five terms computed when the loop ends; a and b show the last two terms.

The order of the shift. The order of the lines a = b; and b = result; matters. If the order is swapped and b = result is written first, the old value of b is lost and the line a = b puts the new term into a. In that case a and b become equal and the sequence turns into one that doubles, like 0 1 1 2 4 8 16 …. In assignments, the variable whose value is going to be overwritten is always updated last.

Java code.

import java.util.Scanner;

public class Fibonacci {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("How many terms? ");
        int n = scanner.nextInt();
        long a = 0, b = 1, result;
        if (n >= 1) System.out.print(a + " ");
        if (n >= 2) System.out.print(b + " ");
        for (int i = 2; i <= n - 1; i++) {
            result = a + b;
            a = b;
            b = result;
            System.out.print(result + " ");
        }
        System.out.println();
        scanner.close();
    }
}

The Java code overlaps the pseudocode line by line. The only difference is that the term variables are chosen as long. Fibonacci terms grow exponentially too. With int, F(46) = 1,836,311,903 is the last correct term. The true value of F(47) is 2,971,215,073 and exceeds the int limit; the program prints −1,323,752,223 instead. Counting the sequence from 0, with F(0) = 0 and F(1) = 1, F(47) is the 48th term of the sequence. So the int program works correctly up to n = 47; when n = 48, the last term it writes is corrupted. With long, correct values are obtained up to F(92). The program prints "0 1 1 2 3 5 8 13" for n = 8 and "0 1 1 2 3 5 8 13 21 34" for n = 10.

Common mistake

An off-by-one error in the loop bound. If the Fibonacci loop is written with i <= n instead of i <= n - 1, the loop runs one iteration too many and n + 1 terms are printed: for n = 5, 0 1 1 2 3 5. Mistakes like this are found most easily by tracing a small test by hand. n = 1 and n = 2 should also be checked separately: in these two cases the loop must not run at all.

1.3.4.3Exponentiation

The power of a number is multiplying the same number by itself repeatedly: baseexp = base × base × … × base (exp times). Also, base0 = 1. The problem is to compute this value for a non-negative integer exponent. Table 1.3.15 gives the test cases; the row where the exponent is 0 is an edge case.

Table 1.3.15: Test cases for exponentiation.
baseexpExpected
3481
2101024
501
Start
    // Enter a number
    Read base
    // Enter an exponent
    Read exp
    // Initialize the result
    result = 1
    // Compute the result using the exponent
    For i = 1 to exp
        result = result * base
    End For
    Print "Result: ", result
End

This algorithm follows the same pattern as the factorial: the accumulator starts at 1 and the loop does one multiplication each iteration. The difference is that the multiplier is the same in every iteration. In the factorial the multiplier is the loop variable i; here it is always base. i is used only to count iterations. When the exponent is 0, the loop condition (1 ≤ 0) is false from the start, the body never runs and the result stays 1.

Table 1.3.16: Trace of the exponentiation algorithm for base = 3, exp = 4.
IterationiOperationresult
start—result = 11
111 × 33
223 × 39
339 × 327
4427 × 381
exit55 ≤ 4 false; "Result: 81" is printed81

Table 1.3.16 shows the four iterations for base = 3, exp = 4. The loop runs exactly exp times; that is, the number of multiplications the algorithm does equals the exponent. For 210, 10 multiplications are made and the result is 1024.

3333×××result = 81
Figure 1.3.8: 34: four multiplications by 3, result 81.

Java code.

import java.util.Scanner;

public class Power {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Base: ");
        int base = scanner.nextInt();
        System.out.print("Exponent: ");
        int exp = scanner.nextInt();
        long result = 1;
        for (int i = 1; i <= exp; i++) {
            result = result * base;
        }
        System.out.println("Result: " + result);
        scanner.close();
    }
}

Java has no exponent operator. Writing 2 ^ 10 compiles but does not exponentiate: ^ is the bitwise "exclusive or" operator, and the value of the expression 2 ^ 10 is 8. A ready-made way is the Math.pow(base, exp) method; however, this method returns a double. Math.pow(3, 4) gives 81.0, not 81, and with very large integers the last digits may be wrong because of the limited precision of double. For integer powers the loop above is a reliable way. Overflow applies here too: had result been int, 231 would give −2,147,483,648 and 232 would give 0. With long the program prints the correct value for 231, 2,147,483,648.

1.3.5Text processing and the flag

The two algorithms in this section bring new tools. The palindrome check works with text rather than numbers and raises the question of how text is compared in Java. The prime check introduces the flag pattern, which gathers the result of a loop in a single boolean variable, and leaving a loop early.

1.3.5.1Palindrome check

Definition 1.3.5

A palindrome is a word or sentence that reads the same backwards as forwards: kayak, abcba, "A man, a plan, a canal: Panama". In sentences, differences of case, spaces and punctuation marks are ignored.

The last sentence of the definition adds a preprocessing step to the algorithm. When the sentence "A man, a plan, a canal: Panama" is reversed letter by letter, it becomes "amanaP :lanac a ,nalp a ,nam A", which is not the same as the original. Capital letters, spaces and punctuation break the comparison. So the text is first cleaned: all letters are converted to lowercase, and characters other than letters and digits are discarded. The cleaned text is "amanaplanacanalpanama", and this text really is equal to its reverse.

Table 1.3.17: Test cases for the palindrome check.
InputClean textExpected
abcbaabcbapalindrome
Kayakkayakpalindrome
Hellohellonot
A man, a plan, a canal: Panamaamanaplanacanalpanamapalindrome

The "Kayak" test checks that capital letters are cleaned, the "Hello" test that an input that is not a palindrome is correctly rejected, and the last test that spaces and punctuation are discarded (Table 1.3.17). The pseudocode has three steps: clean, reverse, compare.

Start
    // Ask for a word or sentence
    Read inputText
    // Clean: lowercase, no spaces or punctuation
    cleanText = Clean(inputText)
    // Reverse the cleaned input
    reversed = Reverse(cleanText)
    // Compare cleaned and reversed input
    If cleanText = reversed then
        Print "The text is a palindrome."
    Else
        Print "The text is not a palindrome."
    End If
End

Clean and Reverse are written in the pseudocode as one-line operations. Each of them is really a small algorithm in its own right. This flexibility of pseudocode is useful: the main idea is set up first and the details of the sub-jobs are left for later.

Hand trace. The trace for the inputs "abcba" and "Hello" is in Table 1.3.18.

Table 1.3.18: Trace of the palindrome algorithm for two tests.
Step“abcba”“Hello”
Read inputTextabcbaHello
cleanText = Clean(…)abcba (no change)hello
reversed = Reverse(…)abcbaolleh
cleanText = reversed ?truefalse (first letter h ≠ o)
ScreenThe text is a palindrome.The text is not a palindrome.
cleanTextabcbareversedabcba
Figure 1.3.9: For "abcba", the clean text and its reverse match letter by letter.

Java code. In the following program the cleaning job is moved into a separate method named clean. For reversing, Java's ready-made StringBuilder class is used.

import java.util.Locale;
import java.util.Scanner;

public class Palindrome {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word or sentence: ");
        String inputText = scanner.nextLine();
        String cleanText = clean(inputText);
        String reversed = new StringBuilder(cleanText).reverse().toString();
        if (cleanText.equals(reversed)) {
            System.out.println("The text is a palindrome.");
        } else {
            System.out.println("The text is not a palindrome.");
        }
        scanner.close();
    }

    static String clean(String text) {
        String lower = text.toLowerCase(Locale.ROOT);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lower.length(); i++) {
            char c = lower.charAt(i);
            if (Character.isLetterOrDigit(c)) sb.append(c);
        }
        return sb.toString();
    }
}

nextLine() reads the whole line. Had next() been used here, only the first word, "A", would be read, because next() stops at a space. Wherever a sentence may be entered, nextLine() is needed.

new StringBuilder(cleanText).reverse().toString() does three jobs in a chain. First a modifiable copy of the text is created, then this copy is reversed in place, and finally it is converted back to a String. In Java, String objects are immutable; reversing a text, concatenating it or changing its letters always produces a new object. StringBuilder, on the other hand, is a modifiable sequence of characters and is designed for such jobs.

The clean method converts the text to lowercase, then walks over the characters one by one. The charAt(i) method gives the character at position i; positions start at 0 and end at length() - 1. Character.isLetterOrDigit(c) says whether a character is a letter or a digit. Letters of any alphabet, Turkish letters included, count as letters; spaces, commas and apostrophes do not. The suitable characters are appended to a StringBuilder and the result is returned.

Comparing text: equals and ==. The most important line of the program is if (cleanText.equals(reversed)). If this line is written as cleanText == reversed, the program compiles and runs but says "not a palindrome" even for "abcba". The reason is what == means for objects. With primitive types such as int, double and char, == compares values. String, however, is an object, and a variable of type String holds not the object itself but its place in memory, that is, a reference to the object. == checks whether two references point to the same object. reversed is a separate object freshly produced by StringBuilder; even if its content is the same as cleanText, it is another object and == gives false. Content comparison is done with the equals method.

This mistake also shows up in a sneaky way. Two identical texts written directly in the source code, String a = "abc"; String b = "abc";, are stored in Java as a single object, and a == b gives true. A programmer sees == working in a small experiment and gains a false confidence. For text read from the user or produced at run time, == gives false almost every time. In an experiment on JDK 21, true was obtained for two literal strings and false for "abcba" and the reverse produced by StringBuilder. The rule is simple: texts are always compared with equals.

Common mistake

Lowercasing text without specifying a locale. When the toLowerCase() method is called without a parameter, it uses the computer's locale. The capital "I" becomes "ı" in a Turkish locale and "i" in an English one: "TITLE".toLowerCase() gives "tıtle" on a computer set to Turkish. The same program can give different results on different computers. In the code above, toLowerCase(Locale.ROOT) is written to fix locale-independent rules. For Turkish text, the Turkish rules are selected with Locale.forLanguageTag("tr"); with that call "Ilık" becomes "ılık", while with Locale.ROOT the same word would become "ilık".

Tests. The program was run on JDK 21 with four tests: for "abcba", "Kayak" and "A man, a plan, a canal: Panama" it prints "The text is a palindrome."; for "Hello" it prints "The text is not a palindrome."

1.3.5.2Prime check

Definition 1.3.6

A prime number is a natural number greater than 1 that is divisible only by 1 and itself: 2, 3, 5, 7, 11, 13, … Numbers greater than 1 that are not prime are called composite numbers.

The definition explicitly leaves two edge cases out: 0 and 1 are not prime. 2 is both the smallest prime and the only even prime. The test cases include these cases and ordinary numbers, both prime and composite (Table 1.3.19).

Table 1.3.19: Test cases for the prime check.
InputExpectedCase tested
0, 1not primeEdge: the loop never runs
2primeEdge: the smallest prime, the loop never runs
7primeThe loop runs to the end
21not primeA divisor is found early
25not primeThe square of a prime
Start
    // Enter a number
    Read num
    // Flag: 0 and 1 are not prime
    If num < 2 then isPrime = False
    Else isPrime = True
    // Try divisors from 2 to half the number
    For divisor = 2 to num / 2
        If num % divisor = 0 then
            // If divisible, not prime
            isPrime = False
            Break
        End If
    End For
    // Print the result based on the flag
    If isPrime = True then
        Print num, " is a prime number."
    Else
        Print num, " is not a prime number."
    End If
End

The algorithm rests on three ideas.

The flag. The isPrime variable is a flag: a variable that takes only the value true or false and records whether a condition has occurred. At the start the number is assumed to be prime and the flag is raised. If the loop finds a divisor, the flag is lowered. When the loop ends, the state of the flag tells the result. The flag pattern is the general solution to questions of the type "is it true for all?": we start with an optimistic assumption, and a single counterexample refutes it.

Remainder and early exit. The condition num % divisor = 0 tests whether the division leaves no remainder: since 21 % 3 = 0, 3 divides 21 exactly. As soon as a divisor is found it is certain that the number is not prime; trying the remaining divisors is pointless. Break (break in Java) leaves the loop at once.

The loop bound. Divisors are tried from 2 to num / 2. Apart from the number itself, no divisor can be larger than half the number. If a divisor d is larger than num / 2, the quotient num / d is less than 2, that is, 1; and this means d = num. num / 2 is integer division: 7 / 2 = 3. For 0 and 1 the bound is 0; the loop never runs and the result is decided by the If num < 2 decision in the first line. For 2 and 3 the bound is 1; the loop again does not run, the flag stays true and both numbers are correctly found prime.

Hand trace. Table 1.3.20 gives the trace for 7 and 21.

Table 1.3.20: Trace of the prime algorithm for 7 and 21.
NumberStepdivisorRemainderisPrime
7 (bound 7 / 2 = 3)7 ≥ 2, flag raised——True
iteration 127 % 2 = 1True
iteration 237 % 3 = 1True
exit: 4 ≤ 3 false4—True
"7 is a prime number."
21 (bound 21 / 2 = 10)21 ≥ 2, flag raised——True
iteration 1221 % 2 = 1True
iteration 2321 % 3 = 0False
Break34 … 10 not triedFalse
"21 is not a prime number."
divisor:234567891021 % 3 = 0 → divides exactly
Figure 1.3.10: The divisors that could be tried for 21 are 2 … 10. 2 does not divide, 3 does; the loop is broken and 4 … 10 are never tried.

Java code.

import java.util.Scanner;

public class IsPrime {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        boolean isPrime = true;
        if (num < 2) isPrime = false;
        for (int divisor = 2; divisor <= num / 2; divisor++) {
            if (num % divisor == 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
            System.out.println(num + " is a prime number.");
        } else {
            System.out.println(num + " is not a prime number.");
        }
        scanner.close();
    }
}

In Java the flag is a variable of type boolean, and its values are true and false. The pseudocode line If isPrime = True then is written in Java as if (isPrime). Since isPrime is already a boolean, there is no need to compare it with true. if (isPrime == true) also works correctly but is needlessly long. if (isPrime = true), however, is an assignment: it compiles, makes isPrime true and always gives the result "prime". With boolean variables, the single-equals mistake slips past the compiler.

The break statement ends the nearest enclosing loop. Program flow moves to the first line after the loop, here the line if (isPrime). Had break not been used, the result would not change; once the flag is lowered, it is not raised again. But the loop would needlessly try seven more divisors, from 4 to 10.

How many divisors are tried? The numbers of divisors the program tries were measured on JDK 21 with a copy that has a counter. For 7, 2 divisors (2, 3) are tried and the number is found prime. For 21, 2 divisors are tried; the loop is broken at 3. For 25, 4 divisors (2, 3, 4, 5) are tried. For 49, 6 divisors are tried and a divisor is found at 7. 97 is prime; the loop tries all 47 divisors from 2 to 48. Primes are the worst case of the algorithm, because the early exit never happens.

A better bound. The bound can be taken as √num instead of num / 2. If a number splits into two factors a × b, one of the factors is no larger than √num. So if no divisor is found up to √num, the number is prime. For 97 this bound is 9, and 8 divisors are tried instead of 47. In Java the condition is written divisor * divisor <= num; this way there is no need to take a square root or use decimal numbers. With large numbers the difference is striking: for a prime around one billion, the num / 2 bound means about 500 million trials, and the √num bound about 31,600.

Common mistake

Forgetting the edge cases. If the line if (num < 2) isPrime = false; is removed, the loop never runs for 0 and 1, the flag stays true and the program declares both numbers prime. 0! in factorial, n = 1 in Fibonacci, and 0 and 1 in the prime check must be tested separately. These inputs are the cases where the algorithm never enters the loop, and the correct result depends entirely on the initial values.

1.3.6Search algorithms

1.3.6.1The search problem

Searching asks whether a particular item is in a collection and, if so, where. It is one of the basic operations of almost every program that processes data. The place of a book in a library, a particular page on a website, a record in a database, a name in a phone book are all found by a search. To define the problem abstractly, imagine a basket and an apple.

Definition 1.3.7

The search problem. The input is a collection of objects (the "Basket") and a particular object (the "Apple"). The output is true if the apple is in the basket and false if not. In programs, instead, the index of the item found, that is, its position in the array, is usually returned; if the item is not found, −1 is returned.

Returning an index gives more information than returning true/false: both the presence and the position of the item are reported with a single number. In Java arrays the valid indices run from 0 to length − 1; since −1 can never be a valid index, it is safely used to mean "not found". Three search methods are examined in these notes (Figure 1.3.11). Random search looks at a random item at each step. Linear search looks at the items in order from start to end. Binary search looks at the middle item and eliminates half of the search space at each step.

238421731548123random order, repeats possible 238421731548left to right, one by one 5121823314248middleeliminatedsearch the right half
Figure 1.3.11: Three search methods. Random search: no order needed, no guarantee of finding. Linear search: no order needed, at most n comparisons. Binary search: the array must be sorted, at most about log2 n comparisons.

The measure for comparing the methods is the number of comparisons: how many times the sought item is compared with an element of the array. This number is independent of the machine, the language and the compiler. If it is known how many comparisons a method makes on a million items, it can be estimated how much faster it will be than the others on whatever computer it runs.

1.3.6.2Random search

Random search checks the items of a collection in a random order. At each step a random item is chosen and compared with the target. If it matches, the search ends; if not, a new random item is chosen. The pseudocode is four steps:

  1. Pick a random item.
  2. Compare the chosen item with the target.
  3. If the target is found, stop.
  4. If not found, repeat the steps.

Figure 1.3.12 shows the search for 48 in an unsorted array of nine items. The randomly chosen items are 23, 42, 7 and 48 in turn; the search ends on the fourth try. If the same search were run again, other items would be chosen and the number of tries would change too.

77042164212323455576487318chosencomparing 48 with 48
Figure 1.3.12: Random search, target 48. The items with red borders (23, 42, 7) are those chosen earlier that did not match; the fourth choice is 48.

Java code. The following method produces random indices with the java.util.Random class. For the method to compile, the line import java.util.Random; must be at the top of the file.

static int randomSearch(int[] array, int target, int maxTries) {
    Random random = new Random();
    for (int attempt = 1; attempt <= maxTries; attempt++) {
        int i = random.nextInt(array.length);   // 0 … length − 1
        if (array[i] == target) {
            return i;
        }
    }
    return -1;   // limit reached; no such item, or just bad luck
}

random.nextInt(array.length) produces a random integer between 0 and array.length - 1, both ends included; this range is exactly the valid indices of the array. The method's third parameter is maxTries. The biggest weakness of random search is that it does not stop if the target is not in the array: every attempt fails and the loop runs forever. This breaks the finiteness property of an algorithm. A try limit solves this problem but brings a new uncertainty. When the limit is reached, −1 is returned. It cannot be known whether this −1 means "the item is not there" or "the item is there but we were unlucky".

How many tries are needed? If there are n items in the array and a single target, the success probability of each try is 1/n. Since the tries are independent, the average number of tries is n. The search for 48 in the nine-item array was repeated 200,000 times on JDK 21 and an average of 9.02 tries was measured. The probability of not finding it at all in n tries is (1 − 1/n)n. For n = 9 this value is about 0.346: one search in three is still without a result after as many tries as there are items. Since the same item can be chosen again and again, even more tries than the worst case of linear search may be needed.

The advantages of random search are its simplicity and its independence of the order of the data. Its disadvantages are serious: there is no guarantee of a definite result, it may choose the same item many times, and if the target is absent it can be stopped only with a try limit. In practice this method is hardly used on its own as a search tool. Its value lies elsewhere: when the search space is too large to try exhaustively, for example in an optimization problem, random sampling is a useful starting point.

1.3.6.3Linear search

Linear search is the most basic way of searching for an item in a collection. Starting from the first, the items are compared with the target in order. If a match is found the position is returned. If the end of the list has been reached, the item is not there. The items need not be sorted.

  1. Put the items into an array.
  2. Starting from the first item, compare in order with the target item.
  3. If the target is found, stop and return its position.
  4. If not found, move on to the next item.
  5. Continue to the end of the list; if the end is reached, the item is not there.
static int linearSearch(int[] array, int target) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == target) {
            return i;
        }
    }
    return -1;
}

The method tries each index of the array in turn. When array[i] == target is true, return i; ends both the method and the loop at once; there is no need for break. If the loop ends without finding a match, flow reaches the last line and −1 is returned. The condition i < array.length stops at length - 1, the last valid index of the array.

Trace. When searching for 23 in the array [42, 17, 8, 23, 31], 42, 17 and 8 do not match; at the fourth comparison array[3] = 23 is found and 3 is returned (Figure 1.3.13). Table 1.3.21 gives the numbers of comparisons for other targets in the same array. The values were verified by running a copy with a counter on JDK 21.

42017182233314icomparing array[0] = 42 with 23 42017182233314iarray[3] = 23: found
Figure 1.3.13: Linear search, target 23. On the left the first comparison (i = 0, 42); on the right the match at the fourth comparison (i = 3).
Table 1.3.21: Linear search in the array [42, 17, 8, 23, 31].
TargetItems looked atComparisonsValue returned
42421 (best case)0
2342, 17, 8, 2343
3142, 17, 8, 23, 3154
5042, 17, 8, 23, 315 (worst case)−1

Cost. In an array of n items, the best case is that the target is the first item: 1 comparison. The worst case is that the target is the last item or is not there at all: n comparisons. If the target is in the array and is equally likely to be at any position, the average is (1 + 2 + … + n) / n = (n + 1) / 2 comparisons. The work grows in direct proportion to n: if the array doubles, the worst-case work doubles too. The algorithm gets its name from this linear growth.

Linear search is simple and easy to understand, works on unsorted data and gives a definite result: if the item exists, it is certainly found. It is the best choice for small collections. Its disadvantage is that it stays slow on large collections. In an array of a million items, a million comparisons are needed for an item that is not there.

1.3.6.4Binary search

Binary search is a fast and efficient way of finding an item in sorted data. The idea is like looking up a word in a dictionary. The dictionary is opened in the middle; if the word comes before the opened page, we move to the left half, and if after, to the right half. At each step the number of pages to look at is halved.

  1. Pick the middle item and compare it with the target.
  2. If the target is found, stop.
  3. If the target is smaller than the middle item, focus on the left half.
  4. If the target is larger than the middle item, focus on the right half.
  5. Repeat until the target is found or the search space is exhausted.

The third and fourth steps rest on the array being sorted. If the target is smaller than the middle item and the array is sorted from smallest to largest, every item in the right half is greater than or equal to the middle one; the target cannot be there. This inference holds only in a sorted array.

static int binarySearch(int[] array, int target) {
    int low = 0, high = array.length - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (array[mid] == target) {
            return mid;
        } else if (target < array[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return -1;
}

The search space is the region between the indices low and high, both ends included. At the start it is the whole array. In each iteration mid = (low + high) / 2 is computed. This is integer division; if the number of items in the space is even, it picks the left of the two middle items. If the target equals the middle item, the index is returned. If it is smaller, high = mid - 1 eliminates the right half and the middle item. If it is larger, low = mid + 1 eliminates the left half and the middle item. In both cases the middle item is not examined again; it has already been compared with the target. The loop condition is low <= high. When low passes high, the search space is empty and the item is not there.

Trace. Let 48 be searched for in the sorted array [7, 12, 23, 31, 42, 48, 55, 64, 77]. Table 1.3.22 shows the variables in each iteration, and Figure 1.3.14 three moments.

Table 1.3.22: Binary search, target 48 in the array [7, 12, 23, 31, 42, 48, 55, 64, 77].
Iterationlowhighmidarray[mid]Decision
108(0 + 8) / 2 = 44248 > 42 → low = 5
258(5 + 8) / 2 = 65548 < 55 → high = 5
355(5 + 5) / 2 = 548equal → return 5
70121232313424485556647778lowmiddlehighmid = (0 + 8) / 2 = 4 → 42 70121232313424485556647778lowmiddlehighmid = (5 + 8) / 2 = 6 → 55 70121232313424485556647778low,mid,highmid = 5 → 48 = 48
Figure 1.3.14: The three iterations of binary search. Items with dashed borders have been eliminated. In the second iteration the search space has four items (48, 55, 64, 77); the left of the two middle ones, 55, is chosen. In the nine-item array only 3 comparisons were made.
Example 1.3.1

Question. If 50 is searched for in the same array, which items are looked at and what does the method return?

Solution. The first two iterations are the same as in the search for 48: mid = 4 (42) and since 50 > 42, low = 5; mid = 6 (55) and since 50 < 55, high = 5. In the third iteration mid = 5, array[5] = 48, and since 50 > 48, low = 6. Now low = 6, high = 5; low <= high is false and the loop ends. The method returns −1 after 3 comparisons. In the final state low shows the position where 50 would have to be in the array: between 48 and 55, index 6.

In the same array, two comparisons suffice for 12 (42 → 12). Four comparisons are needed for 77 (42 → 55 → 64 → 77). In this nine-item array no search exceeds four comparisons. These numbers were verified by running a copy with a counter on JDK 21.

Binary search on an unsorted array. The dangerous side of binary search is that on an unsorted array it gives a wrong result without any error. Let 77 be searched for in the array [77, 42, 64, 12, 23, 55, 7, 48, 31]. The first middle item is 23; since 77 > 23, we move to the right half. Then 7, 48 and 31 are looked at; since 77 is larger than all of them, we keep going right. In the end the space is empty and −1 is returned. Yet 77 is the first item of the array. The method does not check whether the array is sorted and gives no warning. When each of the nine items of this array is searched for separately, only two (23 and 48) are found. And those found happen to fall at the middle positions by chance. On unsorted data the result is left to chance; that is why it is more accurate to say "may give a wrong result on an unsorted array".

How many comparisons? Each iteration halves the search space. A space of n items falls to at most n/2 after one iteration and at most n/4 after two. About log2 n iterations pass until the space falls to a single item; the last item is also looked at once. The worst-case number of comparisons is ⌊log2 n⌋ + 1. For 1,000,000 items, log2 1,000,000 ≈ 19.93; taking the floor and adding one gives 20 comparisons. Linear search can make a million comparisons on the same array.

Common mistake

Off by one at the bounds. If the loop condition is written low < high, the loop stops when a single item is left in the space and that item is never looked at: when searching for 48 in [7, 12, …, 77], the third iteration never runs and −1 is returned. If high = mid or low = mid is written, the space does not shrink in some cases and the loop runs forever. The right pattern is this: the condition low <= high, the updates mid - 1 and mid + 1.

Java's built-in binary search. The Arrays.binarySearch(array, target) method in the java.util.Arrays class implements the same algorithm. If the item is found, it returns its index. If not found, instead of −1 it returns a negative number of the form -(insertionPoint) - 1. The insertion point is the index at which the item would enter the array without breaking the order. For 50 in [7, 12, …, 77] the insertion point is 6, so the method returns −7. A negative result means "not found". This method too assumes the array is sorted; its documentation states explicitly that the result is undefined for an unsorted array.

1.3.6.5Comparing linear and binary search

The difference between the two methods is insignificant on small arrays and striking on large ones (Table 1.3.23).

Table 1.3.23: Number of comparisons in the worst case. The binary search column was computed with the formula ⌊log2 n⌋ + 1 and was also verified by trying all targets for n ≤ 2,000,000.
Number of items nLinear (n)Binary (⌊log2 n⌋ + 1)
994
1001007
1.0001.00010
1.000.0001.000.00020
2.000.0002.000.00021
1.000.000.0001.000.000.00030

The most instructive pair of rows in the table is 1,000,000 and 2,000,000. When the array doubles, the work of linear search doubles too. The work of binary search, however, goes up by only one, because the extra iteration brings the doubled space back to its old size.

This advantage has a price: the data must be sorted, and sorting has a cost too. For a single search, first sorting an array and then binary searching is more expensive than simply searching linearly. Binary search pays off if many searches will be made on the same data, or if the data is kept sorted anyway. That is why phone books and dictionaries are in alphabetical order: they are sorted once and searched millions of times.

Table 1.3.24: Comparison of the three search methods.
RandomLinearBinary
Needs sorted data?NoNoYes
Finds the item if it is there?No guaranteeYesYes (on sorted data)
Stops if the item is absent?Only with a try limitYes, in n comparisonsYes, in ⌊log2 n⌋ + 1 comparisons
Average comparisons (item present)n(n + 1)/2about log2 n

1.3.7Sorting algorithms

1.3.7.1The sorting problem

Sorting arranges the items of a collection by a certain rule. For numbers the rule is usually smallest to largest (ascending) or largest to smallest (descending); for text it is alphabetical order. Sorting is a basic preliminary step of data analysis and of searching. In a sorted array the smallest and largest items are at the ends, the median is in the middle, and repeated items sit side by side. Most importantly, binary search works only on a sorted array.

before421782331after817233142sort (ascending)
Figure 1.3.15: Ascending sort: the array [42, 17, 8, 23, 31] becomes [8, 17, 23, 31, 42].

Three simple methods are examined in these notes. Random sort (shuffling) puts the items in a random order and does not guarantee sorting; it is the opposite job of sorting but uses the same swap operation. Selection sort picks the smallest item and puts it at the front. Bubble sort compares neighboring items and carries the larger one toward the end. There are faster methods too: merge sort and quicksort. Java's built-in Arrays.sort method uses improved forms of these.

The common building block of the three methods is the swap: exchanging two items of the array. In Java there is no single operation that directly exchanges the values of two variables; a swap is done in three steps with a temporary variable.

int temp = array[i];
array[i] = array[j];
array[j] = temp;

The first line copies the value of array[i] to a safe place. The second line writes array[j] over array[i]; the old value of array[i] is now only in temp. The third line puts this value into array[j].

Common mistake

Swapping without a temporary variable. The lines a = b; b = a; make both variables the value of b. If we start with a = 3, b = 5, after the first line a = 5 and 3 is lost. The second line puts 5 into b again. The experiment run on JDK 21 prints "5 5"; the correct swap with a temporary variable prints "5 3".

1.3.7.2Random sort (shuffling)

Random sort, or shuffling, puts the items of a collection in a random order. Shuffling a deck of cards, changing the order of exam questions for each student, and producing random test data for a program are typical uses. Some algorithms also avoid bad cases by shuffling the input first. Quicksort, when its input has been shuffled beforehand, is not affected by specially crafted bad inputs.

Figure 1.3.16 shows the first and last state of shuffling the array [42, 17, 8, 23, 31] three times in a row. The first shuffle produced [31, 17, 42, 8, 23], the second [8, 23, 31, 42, 17], the third [8, 23, 17, 31, 42]. The last array has come close to order but is still not sorted. Shuffling does not guarantee sorting; that is not its purpose either.

42017182233314initial array 802311723134243rd shuffle
Figure 1.3.16: Shuffling. On the left the initial array, on the right the result of the third shuffle: [8, 23, 17, 31, 42]. Each shuffle produces a different result.

A correct shuffle. For a shuffle to count as well done, every arrangement must come up with equal probability. n items have n! different arrangements; each must have probability 1/n!. The classic method that satisfies this condition is the Fisher–Yates shuffle. We start from the end of the array. For each position i, a random j is chosen from 0 to i, both ends included, and array[i] and array[j] are swapped. Then we move one position to the left.

static void shuffle(int[] array) {
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--) {
        int j = random.nextInt(i + 1);   // 0 … i
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

The item that will settle in the last position is chosen with equal probability from each of the n items. The second-to-last position gets one of the remaining n − 1 items, and so on. The total number of choices is n × (n − 1) × … × 2 = n!, and each sequence of choices corresponds to a different arrangement. The method makes exactly n − 1 swaps. The code was run 600,000 times on JDK 21 with the array [1, 2, 3]. Each of the six arrangements was observed between 99,651 and 100,509 times; the expected value is 100,000. In Java the same job is done by the ready-made Collections.shuffle(list) method, which also uses the Fisher–Yates method.

Common mistake

Choosing j from the whole array at every step. A loop that chooses with random.nextInt(array.length) also shuffles the array, but the arrangements do not come out with equal probabilities. This loop produces nn equally likely sequences of choices. Since this number is not divisible by n!, some arrangements come up more often than others. For three items, 33 = 27 sequences of choices cannot be divided evenly among six arrangements: for the array [1, 2, 3], the arrangements [1, 3, 2], [2, 1, 3] and [2, 3, 1] come up with probability 5/27 and the others with 4/27. In 270,000 trials on JDK 21 the first three arrangements were observed about 50,000 times each and the others about 40,000 times each.

Sorting by shuffling. A sorting method can be devised that says "shuffle until the array is sorted". This method is called bogosort and is hopelessly slow. Of the 10! = 3,628,800 different arrangements of 10 items, only one is sorted. The probability that a shuffle produces the sorted array is about one in three and a half million. On average 3.6 million shuffles are needed, each followed by a check for sortedness. For 20 items this number rises to 2.4 × 1018.

1.3.7.3Selection sort

Selection sort is a simple algorithm that sorts by comparing items. The smallest item in the unsorted part of the array is found and moved to the start of that part. Then the unsorted part becomes one item shorter and the process is repeated.

  1. Find the smallest item in the collection.
  2. Move this item to the start of the collection (swap it with the first item).
  3. Find the smallest item in the remaining part.
  4. Move it to the second position.
  5. Repeat these steps to the end of the collection.
static void selectionSort(int[] array) {
    int n = array.length;
    for (int i = 0; i < n - 1; i++) {
        int smallest = i;
        for (int j = i + 1; j < n; j++) {
            if (array[j] < array[smallest]) smallest = j;
        }
        int temp = array[i];
        array[i] = array[smallest];
        array[smallest] = temp;
    }
}

The i variable of the outer loop is the position where the smallest item will settle. The items to the left of i are sorted and in their final places; i and everything to its right is not yet sorted. The inner loop walks from i + 1 to the end of the array and keeps the index of the smallest item seen so far in smallest. This is the classic pattern for finding the smallest item in an array: the first item is taken as the candidate, and the candidate is replaced whenever a smaller item is seen. When the inner loop ends, array[i] and array[smallest] are swapped. The outer loop stops at n - 1, because when the last item is left alone it is already in place.

Step by step. Let the array [64, 25, 12, 22, 11, 36, 48] be sorted. Table 1.3.25 shows each outer iteration, and Figure 1.3.17 the situation before and after the first step and the final state.

Table 1.3.25: Selection sort, [64, 25, 12, 22, 11, 36, 48]. "Comp." is the number of comparisons of the inner loop in that iteration.
Step (i)Unsorted partSmallest (smallest)SwapComp.Array after the step
1 (0)index 0–611 (4)64 ↔ 116[11, 25, 12, 22, 64, 36, 48]
2 (1)index 1–612 (2)25 ↔ 125[11, 12, 25, 22, 64, 36, 48]
3 (2)index 2–622 (3)25 ↔ 224[11, 12, 22, 25, 64, 36, 48]
4 (3)index 3–625 (3)none (already in place)3[11, 12, 22, 25, 64, 36, 48]
5 (4)index 4–636 (5)64 ↔ 362[11, 12, 22, 25, 36, 64, 48]
6 (5)index 5–648 (6)64 ↔ 481[11, 12, 22, 25, 36, 48, 64]
640251122223114365486ismallestsmallest of the unsorted part: 11 110251122223644365486after step 1 110121222253364485646after step 6
Figure 1.3.17: Selection sort. (a) Step 1: the smallest of the unsorted part, 11 (index 4), is about to be swapped with the 64 at position 0. (b) After step 1, 11 is in place (green). (c) After step 6 the array is sorted; the last item has settled into place by itself.

In the fourth step the smallest item is already at the start of the unsorted part; smallest and i are equal. In this case too the code runs the swap lines: the item is swapped with itself and the array does not change. So the number of swaps the code makes is always n − 1; in this example 6. The number of swaps that actually move something is 5. If desired, an if (smallest != i) check can be added before the swap.

Cost. The inner loop makes n − 1 comparisons in the first iteration, n − 2 in the second, and 1 in the last. The total number of comparisons is

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

For 7 items, 7 · 6 / 2 = 21; the sum of the comparisons in the table is also 6 + 5 + 4 + 3 + 2 + 1 = 21. This number does not depend on the initial order of the array. Even if the array is already sorted, selection sort makes 21 comparisons, because to find the smallest it must look at every remaining item. There is no way for the algorithm to notice that the array is sorted. The number of swaps is at most n − 1. This is the strength of selection sort: in situations where writing is expensive, for example in a memory that wears out with each write, making few swaps is an advantage.

Example 1.3.2

Question. When the array [29, 10, 14, 37, 13] is sorted with selection sort, what does the array look like after each step? How many comparisons and how many real swaps are made?

Solution. Step 1: the smallest is 10 (index 1); it is swapped with 29 → [10, 29, 14, 37, 13]. Step 2: among indices 1–4 the smallest is 13 (index 4); it is swapped with 29 → [10, 13, 14, 37, 29]. Step 3: among indices 2–4 the smallest is 14 and it is already in place → [10, 13, 14, 37, 29]. Step 4: the smaller of 37 and 29 is 29; they are swapped → [10, 13, 14, 29, 37]. The number of comparisons is 4 + 3 + 2 + 1 = 10 = 5 · 4 / 2. The number of real swaps is 3; the number of swaps the code makes, counting the swap with itself, is 4.

1.3.7.4Bubble sort

Bubble sort compares items standing side by side. If the left item is larger than the right one, the two are swapped. One such pass from the start of the array to the end is called a pass. During a pass the largest item is carried step by step to the right, like a bubble rising to the surface of water, and settles in the last position of the array at the end of the pass.

  1. Start at the beginning of the collection.
  2. Compare two items side by side; if needed, swap them and carry the larger one to the right.
  3. Repeat this step to the end of the collection (one pass).
  4. Since the largest item has arrived at the end, regard the last item as sorted.
  5. Repeat the first four steps for the remaining part; if no swap happens in a pass, stop.
static void bubbleSort(int[] array) {
    int n = array.length;
    for (int pass = 0; pass < n - 1; pass++) {
        boolean swapped = false;
        for (int j = 0; j < n - 1 - pass; j++) {
            if (array[j] > array[j + 1]) {
                int temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

The pass variable of the outer loop is the number of completed passes. After each pass one more item at the end of the array settles into its final place. That is why the inner loop, with the condition j < n - 1 - pass, stops one item earlier on each pass; there is no point in comparing items that are already in place again. The reason n - 1 is used in the bound of the inner loop is the access array[j + 1]. j can be at most n - 2; otherwise j + 1 runs outside the array.

The swapped variable is again a flag. It is lowered at the start of each pass and raised when a swap is made. If the flag is still down at the end of a pass, no swap happened in that pass. This shows that every neighboring pair is already in the right order, that is, that the array is sorted. break skips the remaining passes. This early stopping feature makes bubble sort fast on sorted or nearly sorted arrays.

Step by step. Let the same array as in selection sort, [64, 25, 12, 22, 11, 36, 48], be sorted with bubble sort. Table 1.3.26 shows the result of each pass, and Figure 1.3.18 the first and last comparison of the first pass and the final state.

Table 1.3.26: Bubble sort, [64, 25, 12, 22, 11, 36, 48]. The step numbers in the slides count each comparison as one step.
IterationStepsComp.SwapArray after the passSettled in place
11–666[25, 12, 22, 11, 36, 48, 64]64
27–1153[12, 22, 11, 25, 36, 48, 64]48
312–1541[12, 11, 22, 25, 36, 48, 64]36
416–1831[11, 12, 22, 25, 36, 48, 64]25
519–2020[11, 12, 22, 25, 36, 48, 64]no swap → stop
Total2011
250641122223114365486jj+1pass 1 · swapped 250121222113364485646jj+1pass 1 · swapped 110121222253364485646array sorted
Figure 1.3.18: Bubble sort. (a) Step 1: 64 > 25, they were swapped. (b) Step 6: 64 has reached the last position. (c) In pass 5 no swap happened; the array is sorted.

In the first pass 64 wins every comparison and travels to the very end with six swaps. In the second pass 25 first passes 12 and 22, then 11; it gets stuck at 36. From then on the bubble is 36, but since 36 < 48 no swap happens; 48 happens by chance to be in its own place already at the end of this pass. The third and fourth passes carry 11 to the left step by step: in bubble sort, small items can move left only one position per pass. Large items near the start of the array go to the end quickly, while small items near the end come to the front slowly. In the fifth pass no swap happens and the algorithm stops. In total 20 comparisons and 11 swaps were made. The values were verified by running a copy with a counter on JDK 21.

Number of swaps and inversions. The number of swaps in bubble sort has a special meaning. Every inversion in the array, that is, a pair made of a larger item on the left and a smaller item on the right, is fixed by exactly one swap. Swapping two neighboring items removes exactly one inversion. So the number of swaps equals the number of inversions in the array. In the array [64, 25, 12, 22, 11, 36, 48], there are 6 items to the right of 64 that are smaller than it; to the right of 25 there are 3 (12, 22, 11), to the right of 12 there is 1 (11), and to the right of 22 there is 1 (11). In total 6 + 3 + 1 + 1 = 11 inversions and 11 swaps.

Cost. The worst case is that the array is in reverse order. In the array [64, 48, 36, 25, 22, 12, 11] every comparison ends in a swap and early stopping never kicks in. 6 + 5 + 4 + 3 + 2 + 1 = 21 comparisons and 21 swaps are made; in general n(n − 1)/2 comparisons and the same number of swaps. The best case is that the array is already sorted. In the first pass n − 1 comparisons are made, no swap happens and the algorithm stops. For 7 items, 6 comparisons suffice. Selection sort still makes 21 comparisons on the same sorted array.

Example 1.3.3

Question. Bubble sort is applied to the array [5, 1, 4, 2, 8]. What does the array look like after the first pass? With early stopping, how many passes, comparisons and swaps are made?

Solution. Pass 1: 5 > 1 swap → [1, 5, 4, 2, 8]; 5 > 4 swap → [1, 4, 5, 2, 8]; 5 > 2 swap → [1, 4, 2, 5, 8]; 5 < 8 no swap. After the pass the array is [1, 4, 2, 5, 8] (4 comparisons, 3 swaps). Pass 2: 1 < 4; 4 > 2 swap → [1, 2, 4, 5, 8]; 4 < 5 (3 comparisons, 1 swap). Pass 3: 1 < 2, 2 < 4; no swap and the algorithm stops (2 comparisons). In total 3 passes, 9 comparisons and 4 swaps. The inversions in the array are (5, 1), (5, 4), (5, 2) and (4, 2); their number is also 4.

Common mistake

Writing the inner loop with j < n. At the last step of the inner loop j = n - 1 and array[j + 1], that is, array[n], is tried to be read. The program stops with a runtime error such as ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7. In every loop that accesses array[j + 1], the upper bound is taken one less.

1.3.7.5Comparing the sorting methods

The properties of the three methods are side by side in Table 1.3.27. The last row gives the values measured for the same seven-item array.

Table 1.3.27: Shuffling, selection sort and bubble sort.
Random (shuffle)SelectionBubble
IdeaProduce a random arrangementPick the smallest, put it at the frontCompare neighbors, carry the larger to the end
Is the result sorted?No guaranteeYesYes
Comparisons (n items)—always n(n − 1)/2worst n(n − 1)/2, n − 1 on a sorted array
Swapsn − 1at most n − 1worst n(n − 1)/2 (as many as the number of inversions)
Example array (n = 7)—21 comparisons, 5 real swaps20 comparisons, 11 swaps

The work of selection sort and bubble sort grows with n2. For 1,000 items, 1000 · 999 / 2 = 499,500, about 500 thousand comparisons are made. For 1,000,000 items this number rises to about 500 billion. Even a computer that makes a billion comparisons a second would spend more than eight minutes on this job. On big data, smarter algorithms are used. The work of methods such as merge sort grows with n · log2 n; for a million items that means about 20 million comparisons. The difference is a factor of about 25,000.

Table 1.3.28: Comparison of five sorting algorithms. The O(…) notation gives how the work grows with n, dropping constant factors.
DetermineIdeaAverageWorstNote
BubbleNeighboring items are compared and swapped if neededO(n2)O(n2)Simple; ineffective on big data
SelectionThe smallest is found and placed at the front; repeat with the restO(n2)O(n2)Slow on big data; few swaps
InsertionThe next item is inserted at the right place in the sorted partO(n2)O(n2)Effective on small or nearly sorted data
MergeSplit in two, sort each half, mergeO(n log n)O(n log n)Effective on big data; needs extra memory
QuickA pivot is chosen; smaller items to the left, larger to the rightO(n log n)O(n2)Very fast on average

Two notations are used in this table: O(n2) and O(n log n). "Big O" notation roughly describes how an algorithm's work grows with the size of its input. Instead of exact numbers, the shape of the growth is given. An algorithm that makes n(n − 1)/2 comparisons is O(n2). As n grows, the term that determines the value of this expression is n2/2; the factor 1/2 does not change the shape of the growth. Linear search is O(n) and binary search is O(log n). This notation is used as a common language for comparing algorithms.

In Java there is no need to rewrite these algorithms every time to sort an array. The call Arrays.sort(array) sorts arrays of primitive types such as int with an improved form of quicksort, and arrays of objects with a method based on merge sort. The purpose of learning the simple algorithms is not to use them in production. The aim is to acquire the habits of looping, comparing, swapping and counting, and to be able to work out the cost of an algorithm on your own.

1.3.8Common mistakes

The most frequent mistakes in the algorithms of this chapter fall into two groups. The first group is mistakes in the algorithm itself: they appear whatever the language is and are found by hand tracing (Table 1.3.29). The second group is specific to Java: it shows up as a message from the compiler or the JVM, and sometimes with no message at all (Table 1.3.30).

Table 1.3.29: Common mistakes at the algorithm level.
MistakeResultThe fix
Initializing the accumulator wrongly: factorial = 0Every product is 0; the result is always 0Start at 0 for addition and at 1 for multiplication
Off by one in the loop bound: i = 2 … n in Fibonaccin + 1 terms are printedTrace the bounds by hand with a small test
Using binary search on an unsorted array−1 for 77 in [77, 42, 64, 12, 23, 55, 7, 48, 31]; no error messageSort first or use linear search
Forgetting edge cases0 and 1 come out prime in the prime checkTest 0, 1, empty input, n = 1 separately
No stopping condition in random searchIf the target is absent the loop runs foreverPut in a try limit
Swapping without a temporary variable: a = b; b = a;Both variables get the value of bSave temp = a first
Writing the shift order backwards in Fibonacci0 1 1 2 4 8 … (a doubling sequence)First a = b, then b = result
Strict < in the three-number comparisons7 5 5 for 5 5 7Use <=
Table 1.3.30: Common Java-specific mistakes. The messages were produced on JDK 21.
MistakeWhat happens?
import java.util.Scanner; forgottenCompile error: error: cannot find symbol … symbol: class Scanner
No ; at the end of the line: int total = 0Compile error: error: ';' expected
Single = in a comparison: if (num % divisor = 0)Compile error: error: unexpected type … required: variable, found: value
Single = with boolean: if (isPrime = true)Compiles; the condition is always true
Comparing strings with ==Compiles but gives false for "abcba" and its reverse; equals must be used
Loop with i <= array.lengthRuntime error: ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
Using int for 13!No error message, wrong result: 1932053504 (correct 6227020800); long must be used
Entering "3.5" on a machine set to TurkishRuntime error: java.util.InputMismatchException
Writing ^ for exponentiation: 2 ^ 10Compiles; the result is 8 (bitwise exclusive or)

A significant share of the mistakes in the tables produce no message at all. Overflow, comparing strings with ==, binary search on an unsorted array and the boolean assignment mistake do not stop the program; they only corrupt the result. The only safeguard against these mistakes is the test cases, prepared when the problem was defined and including the edge cases. With compile errors, on the other hand, the message usually points at the place of the mistake correctly; messages are read starting from the first, because a single missing piece often brings several more messages after it.

1.3.9Summary

  • The problem-solving cycle: define the problem, determine the algorithm, translate to code, test; if there is a bug, go back. Test cases are prepared before the code is written and include edge cases (0, an empty string, equal numbers, n = 1).
  • Algorithm: a sequence of instructions made of clear steps in a definite order and finite in number. Its five properties are input, output, definiteness, finiteness and effectiveness.
  • Pseudocode and hand tracing: pseudocode is a notation written for people, independent of language rules. A trace table shows the variable values at each step and catches loop-bound mistakes without writing code.
  • Translating to Java: Read → nextInt/nextDouble/nextLine with Scanner; Print → print/println; equality ==, assignment =; "and" &&, "or" ||; Break → break. Between two ints, / is integer division.
  • Decision algorithms: sorting two numbers needs a single if … else. With three numbers, the smallest is found first and the remaining two are sorted; <= is needed to handle equalities correctly; all 3! = 6 orders are tested.
  • Loop algorithms: factorial and exponentiation work with an accumulator starting at 1; Fibonacci keeps the last two terms and shifts them each iteration. int is enough up to 12!, F(46) and 230; beyond that it overflows silently. long is enough up to 20! and F(92).
  • Palindrome and prime: the text is first cleaned, reversed and compared with equals. The prime check uses a flag and break; the bound is num / 2, better divisor * divisor <= num.
  • Searching: random search makes n tries on average and gives no guarantee. Linear search makes n comparisons in the worst case and works on unsorted data. Binary search needs sorted data and makes ⌊log2 n⌋ + 1 comparisons in the worst case: 20 for 1,000,000 items.
  • Sorting: a swap uses a temporary variable. The Fisher–Yates shuffle produces every arrangement with equal probability. Selection sort always makes n(n − 1)/2 comparisons and at most n − 1 swaps. Bubble sort makes n(n − 1)/2 comparisons in the worst case; its number of swaps equals the number of inversions, and with early stopping it finishes in n − 1 comparisons on a sorted array. Both are O(n2).

1.3.10Key terms

  • algorithm
  • pseudocode
  • trace table
  • test case
  • edge case
  • dry run
  • accumulator
  • flag
  • overflow
  • compiler
  • bytecode
  • runtime error
  • integer division
  • palindrome
  • prime number
  • linear search
  • binary search
  • random search
  • shuffle
  • selection sort
  • bubble sort
  • swap
  • inversion

1.3.11Test Yourself

  1. The factorial program is run with num = 6. How many iterations does the loop make and what is the result? What would be printed if the loop condition were mistakenly written i < num?

    Answer

    The loop makes 6 iterations for i = 1 … 6; factorial becomes 1, 2, 6, 24, 120, 720 in turn and 720 is printed. With i < num the last factor 6 is skipped and 5! = 120 is printed.

  2. What does the Fibonacci program print for n = 10, and how many iterations does the loop make? If the positions of the lines a = b; and b = result; in the loop body are swapped, what is the output for n = 6?

    Answer

    0 1 1 2 3 5 8 13 21 34; the loop makes n − 2 = 8 iterations for i = 2 … 9. If the lines are swapped, b = result comes first, then a = b gives a the new term as well, and the two variables become equal: 0 1 1 2 4 8.

  3. How many divisors does the prime program try for 49? If the loop condition is changed to divisor * divisor <= num, how many divisors are tried for 97?

    Answer

    For 49 the bound is 49 / 2 = 24; 2, 3, 4, 5, 6 do not divide, 7 does and the loop is broken: 6 tries. With the new condition, for 97 the divisors with d2 ≤ 97 are 2 … 9; none divides and 97 is found prime after 8 tries. The old condition made 47 tries.

  4. What do these three lines print: System.out.println("total " + 2 + 3);, System.out.println(2 + 3 + " total");, System.out.println(7 / 2 * 2);?

    Answer

    "total 23", "5 total" and "6". In the first line the string comes first, so both + are concatenation. In the second, 2 + 3 = 5 is added first. In the third, 7 / 2 becomes 3 by integer division, and 3 * 2 = 6.

  5. In the sorted array {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, which items does binary search look at for 23 and for 4, and what does it return?

    Answer

    23: mid = 4 (16) → right, mid = 7 (56) → left, mid = 5 (23) → found; 3 comparisons, returned value 5. 4: 16 → left, mid = 1 (5) → left, mid = 0 (2) → right; low = 1, high = 0, and after 3 comparisons −1 is returned.

  6. The array [9, 4, 7, 1, 3] is sorted with selection sort. What does the array look like after each step? How many comparisons and how many real swaps are made?

    Answer

    [1, 4, 7, 9, 3] → [1, 3, 7, 9, 4] → [1, 3, 4, 9, 7] → [1, 3, 4, 7, 9]. Comparisons 4 + 3 + 2 + 1 = 10; since in each step the smallest item is at another position, 4 real swaps.

  7. How many passes, comparisons and swaps does bubble sort (with early stopping) make on the arrays [2, 3, 4, 5, 1] and [5, 1, 2, 3, 4]? Although the two arrays have the same number of inversions, why do the numbers of passes differ?

    Answer

    [2, 3, 4, 5, 1]: 4 passes, 4 + 3 + 2 + 1 = 10 comparisons, 4 swaps. [5, 1, 2, 3, 4]: 2 passes, 4 + 3 = 7 comparisons, 4 swaps. Both arrays have 4 inversions, so the numbers of swaps are equal. But while a large item can travel all the way to the end in one pass, a small item moves only one position left per pass. Bringing the 1 at the end to the front takes four passes.

  8. In a sorted array, how many comparisons do linear and binary search make in the worst case for 2,000,000 items? What were the numbers when there were 1,000,000 items?

    Answer

    Linear search 2,000,000; binary search ⌊log2 2,000,000⌋ + 1 = 20 + 1 = 21. For 1,000,000 items the numbers were 1,000,000 and 20. When the array doubles, the work of linear search doubles and that of binary search goes up by one.

  9. In the exponentiation program, if the variable result had been declared int instead of long, what would be printed for 231 and 232? Why is there no error message?

    Answer

    −2147483648 and 0. int holds at most 231 − 1 = 2,147,483,647; one more wraps around to the smallest int value, and one more multiplication turns it into 0. Java does not check integer overflow and throws no exception; the result is silently wrong.

1.3.12Further reading

  • A. B. Downey and C. Mayfield, Think Java (2nd ed., 2019): the chapters on conditionals, loops, strings and arrays complement the Java details of these notes in plain language. The book can be read free online.
  • R. Sedgewick and K. Wayne, Algorithms (4th ed., 2011), Sections 1.1 and 2.1: treats binary search and the basic sorting algorithms with Java code and experimental measurements.
  • P. Deitel and H. Deitel, Java: How to Program (Early Objects) (11th ed., 2017), Chapters 4 and 19: explains algorithm development, pseudocode and search and sort algorithms with many complete programs.
  • D. E. Knuth, The Art of Computer Programming, Vol. 2 (3rd ed., 1997), Section 3.4.2: contains the classic treatment of the Fisher–Yates shuffle and of random permutations.

1.3.13References

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022.
  2. P. Deitel, H. Deitel, Java: How to Program (Early Objects), 11th ed., Pearson, 2017 (Chapter 4: Algorithms and pseudocode; Chapter 19: Searching and sorting).
  3. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.
  4. D. E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd ed., Addison-Wesley, 1997.
  5. D. E. Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.
  6. Oracle, The Java Tutorials: Language Basics, docs.oracle.com/javase/tutorial.
  7. R. Sedgewick, K. Wayne, Algorithms, 4th ed., Addison-Wesley, 2011 (Section 1.1: binary search; 2.1: elementary sorts).

Related pages: Chapter 1.3 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.