4個の要素から成るデータの並びを, 次の手順を繰り返して昇順に整列するとき, 整列が終了するまでに(1)から(3)の一連の手順は, 何回実行されるか。ここで, 最初はデータの並び全体を整列対象とする。 データの並び : [27, 42, 33, 12] 〔手順〕 (1) 整列対象中の要素の最大の値を選び, 最後の要素と入れ替える。 (2) 最後の要素を整列対象から外す。 (3) 整列対象に要素が1個以上残っていれば, (1)から(3)の一連の手順を実行する。残っていなければ, 整列完了なので終了する。
令和7年度 ITパスポート試験 問98
This question's explanation and your answers so far.
問 98
Incorrectア
2 greatly underestimates the number of executions. There are 4 elements, and each pass fixes and removes one, so at least as many passes as needed to reduce the elements are required. After 2 executions, 2 elements still remain in the target and sorting is not complete, so it is wrong.
Incorrectイ
3 is an error from counting with the common impression that “sorting N elements takes N−1 passes.” In this procedure the termination condition is “repeat as long as one or more elements remain,” so even when only 1 element is left in the target, steps (1) to (3) are executed once more before it becomes 0. Therefore it is 4 times, not 3.
- ウ
正解 The procedure is selection sort, repeatedly performing “select the maximum value among the sorting target, swap it with the last element, and remove that last element from the target.” Tracing the target shows that the number of elements decreases one by one as 4→3→2→1→0. The termination condition of step (3) is “repeat as long as one or more elements remain,” so steps (1) to (3) are executed once each when the target has 4, 3, 2, and 1 elements, and processing ends only when the target reaches 0 elements. That is, counting from the initial 4 elements, the number of executions is 4. Therefore the correct answer is ウ (4).
Incorrectエ
5 counts one execution too many. When the target reaches 0 elements, the condition of step (3) is no longer met and processing ends, so steps (1) to (3) are never executed on 0 elements. Execution occurs only when the target has 4, 3, 2, and 1 elements—4 times in total—and a 5th time does not occur, so it is wrong.
- Behavior of selection sort: a repetitive process that selects the maximum (or minimum) value from the sorting target, swaps it into the fixed position (the end), and thereby shrinks the target one element at a time.
- The number of repetitions is determined by the termination condition. In this question, (3) is “repeat as long as one or more elements remain,” so it is executed even when 1 element is left, ending only when the target reaches 0 elements (4 executions for 4 elements).