ProgrammingHardAccenture · Cognizant
A rotated sorted array a = [4, 5, 6, 7, 0, 1, 2] has its smallest element at some index. The procedure below finds that index by a linear scan that keeps the index of the minimum seen so far. What is printed?
A rotated sorted array a = [4, 5, 6, 7, 0, 1, 2] has its smallest element at some index. The procedure below finds that index by a linear scan that keeps the index of the minimum seen so far. What is printed?
best = 0
for i = 1 to n - 1
if a[i] < a[best] then best = i
end for
Print best- A. 3
- B. 4
- C. 5
- D. 6
Correct answer: B. 4
The minimum value 0 sits at index 4, which the scan reaches by replacing the best index only when a strictly smaller value appears. Searching for the maximum gives index 3, reporting a 1-based position gives 5, and the last index is 6.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The loops below print the pairs (i, j) with 1 <= i <= j <= 3 in order, and the procedure prints the total count of pairs. What is printed?…
- Array a = [3, 1, 2]. The procedure below performs a stable count of the number of ways the array can be read in increasing order using…
- Array a = [1, 3, 2, 3, 4, 1] is searched for the longest strictly increasing contiguous run. The procedure below returns its length. What…
- Array a = [5, 1, 4, 2, 3, 7]. The procedure below counts the interior local maxima, that is, positions i from 1 to n - 2 whose value is…
- The KMP prefix function pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it. For s = "abacabab" the…
- Pattern "aba" is searched in the text "abababa" with overlapping matches allowed. The procedure below counts the starting positions where…