Chapter 4.1: Algorithms
Multiple Choice · Problem and Algorithm
Question 1: A Constraint in the Problem Definition
In the definition of the problem “compute the factorial of n using a 64-bit integer (Java long)”, which of the following is a constraint?
D: A constraint is a limit on the values and a validity condition. A describes the input, B the output, and C a small example for checking. 20! = 2,432,902,008,176,640,000 fits in a long, 21! does not; that is why the constraint is 0 ≤ n ≤ 20.
Multiple Choice · Problem and Algorithm
Question 2: Which Is Not an Algorithm?
A good algorithm must be clear, ordered, executable and finite. Which of the following step sequences is not an algorithm because it fails one of these properties?
B: i starts at 1 and only grows; the condition i > 0 is never false, so the steps go on forever (finiteness is violated). In A, i grows each round and the loop ends once it passes n; C and D consist of a single decision anyway.
Output Question · Example Algorithms
Question 3: Swapping Without a Temporary
A student who wants to print two numbers from smaller to larger did not use the variable temp. If a = 7, b = 3 are entered, what is the output?
read a, b if a > b then a = b b = a print a, b
Show answer
Output: 3 3
- 7 > 3 is true → the block is entered.
a = b: a = 3; the old value of a, 7, is lost.b = a: b = 3 (a is now 3).
Correct version: first temp = a, then a = b, b = temp → 3 7.
Multiple Choice · Example Algorithms
Question 4: Initial Value of a Product
In the factorial algorithm, if result = 0 is mistakenly written instead of result = 1, what is printed for n = 5?
read n if n < 0 then print "error" and stop result = 0 // the bug is here i = 2 while i ≤ n result = result × i i = i + 1 print result
A: 0 × i is always 0; the loop runs 4 times but result never changes. The initial value of an accumulator is chosen to suit the operation: 0 for a sum, 1 for a product.
Output Question · Example Algorithms
Question 5: A Boundary Error
In the factorial algorithm, the loop condition is written i < n instead of i ≤ n. What are the outputs for n = 5 and n = 1?
read n result = 1 i = 2 while i < n result = result × i i = i + 1 print result
Show answer
n = 5 → 24, n = 1 → 1
| i (start of round) | 2 | 3 | 4 | 5 |
|---|---|---|---|---|
| i < 5 ? | true | true | true | false |
| result | 2 | 6 | 24 | — |
- When i = 5 the loop ends; ×5 is never done: 4! = 24 is computed (a boundary error, off-by-one).
- For n = 1 the loop does not run anyway and 1 is correct; the bug shows only for n ≥ 2. That is why a single test is not enough.
Output Question · Example Algorithms
Question 6: Assignment Order in Fibonacci
In the Fibonacci algorithm the last two assignments have been swapped. What is the output for n = 6?
read n a = 0, b = 1 for round = 0 to n-1 print a next = a + b b = next // order swapped a = b
Show answer
Output: 0 1 2 4 8 16 (the correct output is 0 1 1 2 3 5)
- After b = next,
a = btakes the new b, not the old one; after the first round a and b are always equal. - From the 2nd round on, next = a + a = 2a → the value doubles.
| round | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| a printed | 0 | 1 | 2 | 4 | 8 | 16 |
| a = b at end of round | 1 | 2 | 4 | 8 | 16 | 32 |
Correct order: first a = b, then b = next.
Step-by-Step Trace · Example Algorithms
Question 7: Palindrome: "Kayık"
The palindrome algorithm is run for the text "Kayık". How many comparisons are made and what is the result?
Converted to lower case: "kayık" (5 letters).
The two ends: lo = 0, hi = 4.
0 < 4 is true. text[0] = 'k', text[4] = 'k' → the same.
Moving inward: lo = 1, hi = 3.
1 < 3 is true. text[1] = 'a', text[3] = 'ı' → different → false is returned.
"Kayık" is not a palindrome. 2 comparisons were enough; the algorithm stops at the first differing pair, and the middle 'y' is never examined.
read text clean text by the rule lo = 0, hi = length - 1 while lo < hi if the characters differ, return false lo = lo + 1, hi = hi - 1 return true
Output Question · Example Algorithms
Question 8: Prime or Not: n = 91
What does the prime-number algorithm print for n = 91? How many times is the % operation performed?
read n if n < 2 then print "not prime" and stop i = 2 while i × i ≤ n if n % i == 0 then print "not prime" and stop i = i + 1 print "prime"
Show answer
Output: not prime, % is performed 6 times.
| i | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|
| i×i ≤ 91 | 4 | 9 | 16 | 25 | 36 | 49 |
| 91 % i | 1 | 1 | 3 | 1 | 1 | 0 |
91 = 7 × 13: since it is not even, it may look prime at first glance. The smaller divisor 7 is less than √91 ≈ 9.5, so it is caught within the bound.
Multiple Choice · Example Algorithms
Question 9: An Error at the Square-Root Bound
In the prime-number algorithm, if the loop condition is written i × i < n instead of i × i ≤ n, for which of the following inputs is a wrong result produced?
A: 49 = 7 × 7. When i = 7, 49 < 49 is false, so the loop ends without trying 7; since 2…6 do not divide it, "prime" is printed. Perfect squares (4, 9, 25, 49…) are the boundary tests that catch this bug. For 21, 3 is found as a divisor; 29 and 2 are prime anyway.
Step-by-Step Trace · Example Algorithms
Question 10: Digit Sum: 472
Trace the completed digit-sum algorithm for number = 472.
The starting value for the sum is 0.
472 > 0 is true. digit = 472 % 10 = 2.
sum = 2; number = 472 / 10 = 47 (integer division, the fraction is discarded).
47 > 0 is true. digit = 7.
sum = 2 + 7 = 9; number = 4.
4 > 0 is true. digit = 4.
sum = 13; number = 4 / 10 = 0.
0 > 0 is false → the loop ends. Number of rounds = number of digits (3).
13 is printed (4 + 7 + 2). The digits were processed from right to left.
read number sum = 0 while number > 0 digit = number % 10 sum = sum + digit number = number / 10 print sum
Multiple Choice · Example Algorithms
Question 11: Number of Digits and 0
The number of digits can be written in two ways. If number = 0 is entered, what is printed, in order?
// I. condition first (while) digits = 0 while number > 0 digits = digits + 1 number = number / 10 print digits // II. condition at the end (do-while) digits = 0 repeat digits = digits + 1 number = number / 10 while number > 0 print digits
B: In I, 0 > 0 is false, so the body never runs → 0 (but 0 has one digit). In II, the body runs at least once before the condition → 1. That is why a check if number == 0 then return 1 is added before the while.
Step-by-Step Trace · Example Algorithms
Question 12: The Smallest Value in a List
The smallest-item solution (pseudocode) is run on the list [7, 3, 9, 1, 4]. How does smallest change?
Start with the first item; a value that is not in the list (e.g. 0) is not assumed.
3 < 7 → true: smallest = 3.
9 < 3 → false: no change.
1 < 3 → true: smallest = 1.
4 < 1 → false: no change.
The result is 1. In a list of 5 items, 4 comparisons were made; each item was examined once.
smallest = first item of the list
for each next item
if item < smallest then
smallest = item
print(smallest)Multiple Choice · Example Algorithms
Question 13: A Maximum Starting at 0
If the algorithm that finds the largest value is started with largest = 0, what does it print for the list [−3, −7, −1, −5]?
A: Since no item in the list is greater than 0, the condition is never true and 0, which is not in the list, is printed. The correct answer should have been −1. That is why the first item of the list is chosen as the initial value.
Output Question · Example Algorithms
Question 14: Average of an Array
The pseudocode of the average solution is below. What is the output for the list [7, 8, 10, 6]?
sum = 0 for each item sum = sum + item average = sum / number of items print(average)
Show answer
Output: 7.75
- sum: 7, 15, 25, 31 → 31 / 4 = 7.75.
- In Java, because
sumand the array length areint,sum / arr.lengthdoes integer division and gives 7. That is why(double) sum / arr.lengthis written. - In an empty list the number of items is 0: the error case must be handled separately.
Multiple Choice · Verification
Question 15: Test Cases
Which row of the test table prepared for the factorial algorithm (constraint 0 ≤ n ≤ 20) is wrong?
C: The value of 21! is correct, but a long holds at most 9,223,372,036,854,775,807; 21! does not fit (overflow). This test shows that the algorithm must check the constraint (n ≤ 20). A single successful test does not prove that the algorithm is correct for every input.
Output Question · Analysis
Question 16: Loop or Formula?
There are two algorithms for the sum 1 + 2 + … + n. What is the result of each for n = 200? How many times is sum = sum + i performed in A, and how many operations are performed in B?
A: sum = 0
i = 1
while i <= n
sum = sum + i
i = i + 1
B: sum = n * (n + 1) / 2Show answer
Both give 20,100.
- A: the body runs 200 times → 200 times sum = sum + i (and 200 counter increments).
- B: 200 × 201 / 2 → independent of n: 1 multiplication + 1 division (plus n + 1).
Efficiency matters as much as correctness: as n grows, A’s work grows, while B’s stays constant.
Step-by-Step Trace · Search
Question 17: Binary Search: 27
27 is being searched for in the array {2, 5, 9, 14, 20, 27, 33}. Trace the values of lo, hi and mid in each round.
The range is the whole array: 0…6.
0 ≤ 6 is true, round 1. mid = 0 + 6/2 = 3, arr[3] = 14.
14 ≠ 27; 14 < 27 → the target is in the right half: lo = 4.
4 ≤ 6 is true, round 2. mid = 4 + (6 − 4)/2 = 5, arr[5] = 27.
27 == 27 → return 5. Found in 2 rounds; linear search would have made 6 comparisons.
int binarySearch(int[] arr, int target) { int lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; }
Output Question · Search
Question 18: Binary Search: A Missing Value
If 4 is searched for by binary search in the sorted array {2, 5, 9, 14, 20, 27, 33}, how many rounds are made, what are lo / hi / mid in each round, and what is returned?
Show answer
| round | lo | hi | mid | arr[mid] | decision |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 14 | 14 > 4 → hi = 2 |
| 2 | 0 | 2 | 1 | 5 | 5 > 4 → hi = 0 |
| 3 | 0 | 0 | 0 | 2 | 2 < 4 → lo = 1 |
| — | 1 | 0 | 1 ≤ 0 is false → the loop ends | ||
3 rounds, result −1. 4 would lie between 2 and 5; when lo passes hi the range becomes empty. For 7 items at most ⌊log₂ 7⌋ + 1 = 3 rounds.
Multiple Choice · Search
Question 19: Binary Search in an Unsorted Array
What happens if binary search is run for 5 on the unsorted array {7, 3, 9, 5, 1}?
C: Round 1: mid = 2, 9 > 5 → hi = 1 (the right side, where 5 is, was eliminated by mistake). Round 2: mid = 0, 7 > 5 → hi = −1; 0 ≤ −1 is false → −1. Eliminating half is safe only if the array is sorted.
Multiple Choice · Search
Question 20: Comparisons in the Worst Case
A value that is not present is searched for in a sorted array of 1000 items. In the worst case, how many comparisons does linear search make and how many rounds does binary search make?
A: Linear search looks at all n = 1000 items: O(n). Binary search halves the range in each round: ⌊log₂ 1000⌋ + 1 = 9 + 1 = 10 rounds, O(log n). For n = 1,000,000 the difference is 1,000,000 versus 20.
Step-by-Step Trace · Sorting
Question 21: Selection Sort
The array [6, 2, 8, 3] is sorted with selection sort. How do minIdx and the array change in each pass, and how many comparisons are made in total?
i = 0: the candidate minimum is arr[0] = 6.
j = 1: 2 < 6 → minIdx = 1. j = 2: 8 < 2 no. j = 3: 3 < 2 no.
arr[0] and arr[1] are swapped → 2 is in place.
i = 1: minIdx = 1 (6). j = 2: 8 < 6 no. j = 3: 3 < 6 → minIdx = 3.
arr[1] and arr[3] are swapped → 3 is in place.
i = 2: minIdx = 2 (8). j = 3: 6 < 8 → minIdx = 3.
Swap → the array is sorted. 3 + 2 + 1 = 6 = n(n−1)/2 comparisons, 3 swaps.
for i = 0 to n-2 minIdx = i for j = i+1 to n-1 if arr[j] < arr[minIdx] then minIdx = j swap arr[i] and arr[minIdx]
Output Question · Sorting
Question 22: Bubble Sort
Bubble sort with early stopping is applied to the array [6, 2, 8, 3]. What is the array at the end of each pass; how many passes and how many comparisons are made?
round = 0 repeat swapped = false for j = 0 to n-2-round if arr[j] > arr[j+1] then swap arr[j] and arr[j+1] swapped = true round = round + 1 until swapped is false
Show answer
| pass | pairs compared | after |
|---|---|---|
| 1 | (6,2)↔ (6,8) (8,3)↔ | [2, 6, 3, 8] |
| 2 | (2,6) (6,3)↔ | [2, 3, 6, 8] |
| 3 | (2,3) | no swap → stop |
3 passes, 3 + 2 + 1 = 6 comparisons, 3 swaps. The array was sorted in the 2nd pass, but the 3rd pass is needed to notice it: swapped = false.
Output Question · Sorting
Question 23: Insertion Sort
Insertion sort is applied to the array [6, 2, 8, 3]. What is the array for each i, and how many arr[j] > key comparisons are made in total?
for i = 1 to n-1 key = arr[i] j = i - 1 while j >= 0 and arr[j] > key arr[j+1] = arr[j] j = j - 1 arr[j+1] = key
Show answer
| i | key | comparisons | after |
|---|---|---|---|
| 1 | 2 | 6>2 ✓ (j = −1 stops) | [2, 6, 8, 3] |
| 2 | 8 | 6>8 ✗ | [2, 6, 8, 3] |
| 3 | 3 | 8>3 ✓ 6>3 ✓ 2>3 ✗ | [2, 3, 6, 8] |
A total of 1 + 1 + 3 = 5 comparisons. When j = −1, j >= 0 is false, so arr[j] is never read.
On [6, 2, 8, 3], selection sort and bubble sort make 6 comparisons each; insertion sort is the fastest on nearly sorted data.
Multiple Choice · Sorting
Question 24: Sorting a Sorted Array
For the already sorted array [1, 2, 3, 4, 5], which pairing is correct (number of comparisons made)?
B: Selection sort makes n(n−1)/2 = 10 comparisons whatever the input (even its best case is O(n²)). Bubble sort makes 4 comparisons in the first pass and stops because there was no swap. In insertion sort there is one comparison per key: 4 → O(n).