問題
次の擬似言語プログラムは配列を二分探索する。探索対象target=50のとき、ループが終了したときのfoundの値はどれか。
整数型の配列: data ← {10, 20, 30, 40, 50, 60, 70}
整数型: target ← 50
整数型: low ← 1
整数型: high ← 7
論理型: found ← false
while (low ≦ high and found = false)
整数型: mid ← (low + high) / 2
if (data[mid] = target)
found ← true
elseif (data[mid] < target)
low ← mid + 1
else
high ← mid - 1
endif
endwhile
選択肢
- 1ア true
- 2イ false
- 3ウ 50
- 4エ 0
正解
1. ア true
詳しい解説を見る解説を閉じる
解説
二分探索でtarget=50を探します。mid=(1+7)/2=4(小数切捨)、data[4]=40<50なのでlow=5。mid=(5+7)/2=6、data[6]=60>50なのでhigh=5。mid=(5+5)/2=5、data[5]=50で一致、found=true。
一問一答
科目A 180問+科目B 60問