Skip to content

令和5年度 ITパスポート試験 問60

This question's explanation and your answers so far.

問60
頻出度★★☆

手続 printArray は,配列 integerArray の要素を並べ替えて出力する。手続 printArray を呼び出したときの出力はどれか。ここで,配列の要素番号は 1 から始まる。 〔プログラム〕 ○printArray() 整数型: n, m 整数型の配列: integerArray ← {2, 4, 1, 3} for (n を 1 から (integerArray の要素数 − 1) まで 1 ずつ増やす) for (m を 1 から (integerArray の要素数 − n) まで 1 ずつ増やす) if (integerArray[m] > integerArray[m + 1]) integerArray[m] と integerArray[m + 1] の値を入れ替える endif endfor endfor integerArray の全ての要素 を先頭から順にコンマ区切りで出力する

出典 令和5年度 ITパスポート試験 問60
解説

問 60

  • ア

    正解 This program compares two adjacent elements and swaps them when the left one is greater than the right one — a bubble sort (ascending order). The initial array is {2, 4, 1, 3}. The outer variable n runs from 1 to 3, and the inner variable m runs from 1 to (4 − n). In the n=1 pass (m=1 to 3), {2,4,1,3}→{2,1,4,3}→{2,1,3,4}; in the n=2 pass (m=1 to 2), {2,1,3,4}→{1,2,3,4}; in the n=3 pass (m=1) no swap occurs, so it stays {1,2,3,4}. Therefore the output is 1, 2, 3, 4, and the correct answer is ア.

  • Incorrectイ

    1, 3, 2, 4 has 2 and 3 in reversed order, so it is not sorted in ascending order. When each pass is carried out to the end, 2 comes before 3, so this arrangement does not occur.

  • Incorrectウ

    3, 1, 4, 2 is not sorted; it is a wrong result that processes the initial array only partway (or mistakes the comparison condition). The program performs all passes and sorts completely into ascending order.

  • Incorrectエ

    4, 3, 2, 1 is descending order. The condition of this program is to swap when the left value is greater than the right value, which is an ascending sort that moves larger values toward the back, so it does not produce descending order.

ここがポイント
  • Bubble sort is an algorithm that sorts by comparing and swapping adjacent elements. The condition swap when integerArray[m] is greater than integerArray[m+1] means an ascending sort that carries larger values to the end.
  • For a double loop in pseudocode, trace the array values one by one to obtain the answer reliably. The key point is that the inner loop's upper bound is (number of elements − n), which excludes the already-fixed tail elements from the comparison.
用語

Your answers