ITPEC FE Subject B April 2025 Question 11

Topic: Sorting

From the answer group below, select the correct combination of answers to be inserted into A in the description and B in the program. Here, the array index starts at 0.

The procedure sort receives an integer array arr and prints all the integers in arr in ascending order, separated by commas. The number of elements in arr is ≥ 1. The values of all array elements are in the range of 0-10.

If arr is {9, 3, 2, 0, 9, 3, 0, 1, 5, 3, 8}, at the end of the procedure, it outputs "0, 0, 1, 2, 3, 3, 3, 5, 8, 9, 9, " and the values of the elements of array s will be {A}

[Program]
○ sort(integer []: arr) // prints all the elements in arr in ascending order
integer []: s ← {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
integer: i, j
for (increase i from 0 to (the number of elements in arr) - 1 by 1)
s[arr[i]] ← s[arr[i]] + 1
endfor
for (increase i from 0 to 10 by 1)
if (s[i] > 0)
for (increase j from 0 to s[i] - 1 by 1)
output B and ", "
endfor
endif
endfor
return

Answer group

OptionAB

Explanation

A: 2, 1, 1, 3, 0, 1, 0, 0, 1, 2, 0 and B: i — s is a counting array: s[v] holds how many times the value v occurs in arr, and the second loop prints each index as many times as it was counted.

The first loop adds 1 to s[arr[i]] for every element, so each index of s counts one of the values 0–10. For {9, 3, 2, 0, 9, 3, 0, 1, 5, 3, 8}:

Value012345678910
Count21130100120

The second loop walks i from 0 to 10, and for each non-zero count the inner loop runs s[i] times. What must be printed is the value itself, which is the index i: 0 twice, 1, 2, 3 three times, 5, 8, 9 twice — exactly the expected output.

Answer (g)

Why not others:

  • •(a), (b) and (c) — blank A lists the sorted output; s holds counts, and the program never stores sorted values anywhere, it only prints them
  • •(d), (e) and (f) — blank A lists the distinct values present; those are the indices where s is non-zero, not what s contains
  • •(h) — prints j, the repeat counter, so the output is 0, 1, 0, 0, 0, 1, 2, 0, 0, 0, 1 instead of the values
  • •(i) — prints s[j], a count read at the repeat-counter position (2, 1, 2, 2, …), again a frequency rather than a value

Key rule: In counting sort the index of the count array is the value and the element is its frequency, so output each index as many times as its count.

Sorting · AI-written, may contain errors

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.