ProgrammingHardCapgemini · Infosys pattern
What will be the output of the following pseudocode? (Arrays are indexed from 0.)
What will be the output of the following pseudocode? (Arrays are indexed from 0.)
Integer arr[6] = {5, 2, 9, 1, 5, 6}
for (each i from 1 to length(arr) - 1)
Integer key = arr[i]
Integer j = i - 1
while (j >= 0 and arr[j] > key)
arr[j + 1] = arr[j]
j = j - 1
end while
arr[j + 1] = key
end for
Print arr- A. [1, 2, 5, 5, 6, 9]
- B. [5, 2, 9, 1, 5, 6]
- C. [1, 2, 5, 6, 5, 9]
- D. [9, 6, 5, 5, 2, 1]
Correct answer: A. [1, 2, 5, 5, 6, 9]
This is insertion sort: each key is shifted left past larger elements until it finds its correct spot. Applying it to {5,2,9,1,5,6} fully sorts the array into [1, 2, 5, 5, 6, 9].
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer arr[5] = {2, 4, 6, 8, 10} Integer prefix[6]…
- What will be the output of the following pseudocode? Integer moves = 0 Function hanoi(Integer n) if (n == 0) return end if hanoi(n - 1)…
- What will be the output of the following pseudocode? Function isPalindrome(String s) Integer i = 0, j = length(s) - 1 while (i < j) if…
- What will be the output of the following pseudocode? (Arrays are indexed from 0.) Integer arr[5] = {1, 2, 3, 4, 5} Integer s = 0 for (each…
- What will be the output of the following pseudocode? (Matrices are indexed from 0.) Integer mat[3][2] = {{1, 2}, {3, 4}, {5, 6}} Integer…
- What will be the output of the following pseudocode (merging two sorted arrays)? (Arrays are indexed from 0.) Integer a[4] = {1, 3, 5, 7}…