IPA FE Subject B 2024 Question 4

Topic: Sorting

A question IPA Japan published in 令和6年度 基本情報技術者試験 科目B 公開問題 問4, translated into English. ITPEC is based on the same exams.

From the answer group below, select the correct answer to be inserted into blank in the description. Here, the array index starts at 1.

The function merge receives the integer-type arrays data1 and data2, which are sorted in ascending order, and returns an integer-type array sorted in ascending order that is made by merging them.
When the function merge is called as merge({2, 3}, {1, 4}), the line /*** α ***/ is blank.

[Program]
○ integer []: merge(integer []: data1, integer []: data2)
integer: n1 ← the number of elements in data1
integer: n2 ← the number of elements in data2
integer []: work ← {(n1 + n2) undefined}
integer: i ← 1
integer: j ← 1
integer: k ← 1
while ((i ≤ n1) and (j ≤ n2))
if (data1[i] ≤ data2[j])
work[k] ← data1[i]
i ← i + 1
else
work[k] ← data2[j]
j ← j + 1
endif
k ← k + 1
endwhile
while (i ≤ n1)
work[k] ← data1[i]
i ← i + 1
k ← k + 1
endwhile
while (j ≤ n2)
work[k] ← data2[j] /*** α ***/
j ← j + 1
k ← k + 1
endwhile
return work

Answer group

Explanation

Executed once — the first loop merges until one array runs out, and the α line only copies what is left of data2 after that.

With data1 = {2, 3} and data2 = {1, 4}, so n1 = n2 = 2, the first while loop runs while both arrays still have elements:

PassCompareCopied to work[k]i, j, k after
12 ≤ 1 is falsedata2[1] = 11, 2, 2
22 ≤ 4 is truedata1[1] = 22, 2, 3
33 ≤ 4 is truedata1[2] = 33, 2, 4

Now i = 3 > n1, so the first loop ends and the second loop (the rest of data1) does not run. The third loop runs while j ≤ 2: it copies data2[2] = 4 into work[4] on the α line, and j becomes 3, ending it. The line runs exactly once, and work is {1, 2, 3, 4}.

Answer (b)

Why not others:

  • •(a) — would hold only if data2 ran out first; here data1's last value 3 is smaller than data2's 4, so 4 is still left over
  • •(c) — counts both elements of data2, but data2[1] = 1 was already copied in the first loop, not on the α line
  • •(d) — counts the three passes of the first loop, which run the lines above, not the α line

Key rule: In a merge, after the main loop only one array has elements left, and the leftover loop for an array runs once per element still left in it: here the elements of data2 greater than the last element of data1.

Sorting · AI-written, may contain errors

This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.