Chapter 1.3: Algorithms

Chapter 1.3: Algorithms · Study Questions
Properties of an algorithmTest casesTurning ideas into codeFactorial and FibonacciPalindrome and primeLinear searchBinary searchSelection sortBubble sort
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Problem Solving

Question 1: “Add a Little Salt”

A step like “add a little salt” in a recipe is not enough for a computer. Which property of an algorithm does this step violate?

B: Definiteness requires every step to be clear and unambiguous; “a little” varies from person to person. Finiteness means the algorithm ends, effectiveness means every step can actually be carried out.

Multiple Choice · Problem Solving

Question 2: Edge Case

Test cases are being written for a program that counts the words in a text. Which one is an edge case test?

D: Extreme inputs such as an empty text, zero or a negative number are where bugs hide most often; the expected output is written in advance. A, B and C are ordinary inputs.

Multiple Choice · Turning Ideas into Code

Question 3: print and println

What does the code print to the screen?

double a = 7, b = 2;
System.out.print(a / b);
System.out.println(" " + (int) a / 2);

A: a and b are doubles, so a / b = 3.5. print does not start a new line, so println continues on the same line. (int) a is applied first (7), then 7 / 2 is integer division = 3.

Step-by-Step Trace · Example Algorithms

Question 4: Is It Prime: 91

What does the program print? How many divisors does the loop try?

divisors tried (remainder below)

91 ≥ 2: the flag stays true. Loop limit 91 / 2 = 45.

21

91 % 2 = 1 ≠ 0, continue.

2131

91 % 3 = 1 ≠ 0, continue.

213143

91 % 4 = 3 ≠ 0, continue.

21314351

91 % 5 = 1 ≠ 0, continue.

2131435161

91 % 6 = 1 ≠ 0, continue.

213143516170

91 % 7 = 0 → divides exactly (91 = 7 · 13). The flag is lowered and break leaves the loop.

213143516170

Flag is false → else branch. 6 divisors were tried; 8–45 were never tried.

int number = 91;
boolean isPrime = true;
if (number < 2) isPrime = false;
for (int divisor = 2; divisor <= number / 2; divisor++) {
    if (number % divisor == 0) {
        isPrime = false;
        break;
    }
}
if (isPrime) System.out.println(number + " is prime");
else System.out.println(number + " is not prime");

Output Question · Example Algorithms

Question 5: Fibonacci: n = 8

What does the program print? How many times does the for loop run?

int n = 8;
int 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 + " ");
}
Show answer
0 1 1 2 3 5 8 13 

The first two terms (0, 1) are printed before the loop. The loop runs for i = 2 … 7, 6 times (n − 2): 1, 2, 3, 5, 8, 13.

In each round a = b; b = result; shifts the last two terms one step. If these two lines are swapped, the result breaks.

Spot the Bug · Example Algorithms

Question 6: Two Bugs in Factorial

The code was supposed to print 5! = 120. What does it print? Find and fix the two bugs.

int number = 5;
int factorial = 0;
for (int i = 1; i < number; i++) {
    factorial = factorial * i;
}
System.out.println(factorial);
Show answer
0

(1) The accumulator starts at 0, so every product is 0. The identity element for multiplication is 1: factorial = 1.

(2) i < number skips the last factor (5): it must be i <= number. After the fix, 120 is printed. Because 13! does not fit in an int, use long for larger numbers.

Multiple Choice · Example Algorithms

Question 7: == in a Palindrome

In the palindrome program, clean.equals(reversedInput) was changed to clean == reversedInput. For the input "abcba", what does the condition evaluate to?

String clean = "abcba";
String reversedInput = new StringBuilder(clean)
        .reverse().toString();
if (clean == reversedInput) { /* ... */ }

C: reversedInput is created as a new object by StringBuilder; even though the contents are equal, they are two separate objects and == gives false. The code compiles (A is wrong). Content comparison is done with equals.

Output Question · Example Algorithms

Question 8: Summing the Digits

What does the program print?

int number = 4071, sum = 0, steps = 0;
while (number > 0) {
    sum += number % 10;
    number = number / 10;
    steps++;
}
System.out.println(sum + " " + steps);
Show answer
12 4
roundnumber % 10sumnumber
111407
27840
3084
44120

% 10 gives the last digit, / 10 drops it. steps is the number of digits.

Multiple Choice · Search Algorithms

Question 9: Binary Search on an Unsorted Array

{77, 42, 64, 12, 23, 55, 7, 48, 31} is searched for 77 using binary search. What happens?

C: The method looks at 23, 7, 48 and 31 in turn: 77 is greater than all of them, so it always goes right and the 77 at index 0 is never examined; −1 is returned. Binary search assumes sorted data; it does not check this and gives no warning.

Step-by-Step Trace · Search Algorithms

Question 10: Binary Search: 41

{3, 9, 14, 20, 27, 33, 41, 50, 58, 66} is searched for 41. Which elements are examined and what does the method return?

3091142203274335416507588669

The search range is the whole array: low = 0, high = 9.

3091142203274335416507588669

mid = (0 + 9) / 2 = 4 → 27. 41 > 27: right half, low = 5.

3091142203274335416507588669

mid = (5 + 9) / 2 = 7 → 50. 41 < 50: left half, high = 6.

3091142203274335416507588669

mid = (5 + 6) / 2 = 5 → 33. 41 > 33: right half, low = 6.

3091142203274335416507588669

mid = (6 + 6) / 2 = 6 → arr[6] = 41: found, return 6. 4 comparisons were enough.

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

Multiple Choice · Search Algorithms

Question 11: Worst Case

If the item being searched for is not in a sorted array of 100 elements, what is the maximum number of comparisons that linear and binary search make?

A: Linear search looks at every element: 100. Binary search halves the range at each step: ⌊log₂ 100⌋ + 1 = 6 + 1 = 7 (100 → 50 → 25 → 12 → 6 → 3 → 1). When n doubles, the work of binary search grows by only one.

Output Question · Search Algorithms

Question 12: How Many Times Does It Occur?

What does this variant of linear search print?

int[] arr = {5, 8, 3, 8, 1, 8};
int first = -1, last = -1, count = 0;
for (int i = 0; i < arr.length; i++) {
    if (arr[i] == 8) {
        if (first == -1) first = i;
        last = i;
        count++;
    }
}
System.out.println(first + " " + last
        + " " + count);
Show answer
1 5 3

8 is at indices 1, 3 and 5. first is assigned only on the first match (while it is −1); last is updated on every match.

Because there is no return, the loop runs to the end: even if the target is found, 6 comparisons are made.

Output Question · Sorting Algorithms

Question 13: Selection Sort

Selection sort prints the array after each outer pass. What is the output? How many comparisons are made in total?

int[] arr = {40, 15, 32, 8, 21};
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
    int minIndex = i;
    for (int j = i + 1; j < n; j++)
        if (arr[j] < arr[minIndex]) minIndex = j;
    int temp = arr[i];
    arr[i] = arr[minIndex];
    arr[minIndex] = temp;
    System.out.println(Arrays.toString(arr));
}
Show answer
[8, 15, 32, 40, 21]
[8, 15, 32, 40, 21]
[8, 15, 21, 40, 32]
[8, 15, 21, 32, 40]

Pass 1 swaps the smallest element, 8, with 40; in pass 2, 15 is already in place (swap with itself); pass 3 swaps 21 ↔ 32; pass 4 swaps 32 ↔ 40.

Comparisons: 4 + 3 + 2 + 1 = 10 = n(n − 1)/2; this does not change even if the array is sorted.

Step-by-Step Trace · Sorting Algorithms

Question 14: Bubble Sort

{6, 2, 9, 1, 5} is sorted with bubble sort. How many passes, comparisons and swaps are made?

6021921354

Start. In each pass neighbours are compared; the larger one moves right.

2061921354

pass 0, j = 0: 6 > 2 → swap.

2061921354

pass 0, j = 1: 6 ≤ 9, no change.

2061129354

pass 0, j = 2: 9 > 1 → swap.

2061125394

pass 0, j = 3: 9 > 5 → swap. Pass finished: 9 is in its final place.

2061125394

pass 1, j = 0: 2 ≤ 6, no change.

2011625394

pass 1, j = 1: 6 > 1 → swap.

2011526394

pass 1, j = 2: 6 > 5 → swap. Pass finished: 6 is in its final place.

1021526394

pass 2, j = 0: 2 > 1 → swap.

1021526394

pass 2, j = 1: 2 ≤ 5, no change. Pass finished: 5 is in its final place.

1021526394

pass 3, j = 0: 1 ≤ 2, no change.

1021526394

No swap happened in this pass: the array is sorted, break. Total: 10 comparisons, 6 swaps, 4 passes.

for (int pass = 0; pass < n - 1; pass++) {
    boolean swapped = false;
    for (int j = 0; j < n - 1 - pass; j++) {
        if (arr[j] > arr[j + 1]) {
            int temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
            swapped = true;
        }
    }
    if (!swapped) break;
}

Multiple Choice · Sorting Algorithms

Question 15: Comparisons in Selection Sort

How many comparisons does selection sort make on an 8-element array? What would change if the array were already sorted?

D: n(n − 1)/2 = 8 · 7 / 2 = 28. To find the smallest, selection sort must look at every remaining element; whether the array is sorted does not change this. It is bubble sort with early stopping that drops to n − 1 (A confuses the two).

Multiple Choice · Sorting Algorithms

Question 16: The swapped Flag

What is the purpose of the swapped flag in bubble sort?

B: If no swap happened in a pass, all neighbours are already in the right order; break skips the remaining passes. A sorted array needs only n − 1 comparisons. A describes minIndex in selection sort, and D describes the temp variable.

The End

Chapter 1.3: Algorithms: Study Questions
Lecture slides: Chapter 1.3: Algorithms · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.