手続 sort は,要素数が2以上の整数型の配列を引数 numberArray で受け取り,その要素を昇順に並べ替えた結果を出力する。手続 sort の動作確認のために,処理の途中で j の値と workArray の全ての要素を出力する。配列 numberArray を {3, 5, 1, 2, 4} とし,手続 sort を sort(numberArray) として呼び出したとき,j の値が3と出力された直後の workArray の全ての要素の出力はどれか。ここで,配列の要素番号は1から始まる。 〔プログラム〕 ○sort(整数型の配列: numberArray) 整数型: minIndex, j, k 整数型の配列: workArray ← numberArray // 配列の複製を作る for (j を 1 から (workArray の要素数 − 1) まで 1 ずつ増やす) // j 番目から末尾までの要素の中で最も小さい値をもつ要素の要素番号を // 一つ求める minIndex ← j for (k を (j + 1) から workArray の要素数 まで 1 ずつ増やす) if (workArray[k] が workArray[minIndex] より小さい) minIndex ← k endif endfor workArray[j] と workArray[minIndex] の値を入れ替える // 動作確認のために,j の値と workArray の全ての要素を出力する j の値を出力する workArray の全ての要素 を先頭から順にコンマ区切りで出力する endfor workArray の全ての要素 を先頭から順にコンマ区切りで出力する
令和8年度 ITパスポート試験 問67
This question's explanation and your answers so far.
問 67
Incorrectア
1,2,3,4,5 is the final result fully sorted in ascending order, which appears immediately after the j=4 output (after swapping the trailing 5 and 4). Right after j=3 the tail is still …5,4, so this is wrong.
- イ
正解 This procedure is a selection sort: for each j it finds the smallest element from the j-th to the last, and swaps that element with the j-th one. Let workArray be the same as numberArray, {3,5,1,2,4}, and trace it using element numbers starting from 1. At j=1, the minimum value 1 (the 3rd element) is swapped with the 1st, giving {1,5,3,2,4}. At j=2, the minimum value 2 (the 4th element) of the remaining {5,3,2,4} is swapped with the 2nd, giving {1,2,3,5,4}. At j=3, the minimum of the remaining {3,5,4} is 3, which is already in the 3rd position, so it is swapped with itself and the array stays {1,2,3,5,4}. Therefore, immediately after the value of j is output as 3, workArray is 1,2,3,5,4, so イ is correct.
Incorrectウ
The arrangement 4,5,3,2,1 never appears at any point in the trace starting from the initial state {3,5,1,2,4}. It does not match the behavior of selection sort, which fixes the minimum value starting from the front, so it is wrong.
Incorrectエ
5,4,3,2,1 is arranged in descending order, but this procedure sorts in ascending order, and this arrangement does not occur at any stage of the process. It is a wrong answer that confuses descending order with ascending order.
- Selection sort: in each round j, find the smallest element from the j-th to the last, and swap its element number minIndex with the j-th. If the smallest element is already at the j-th position, it is swapped with itself (effectively no change).
- The key to tracing pseudocode is to manually follow the array step by step using element numbers starting from 1, and to read the array state immediately after the swap at each j.