Predict the output
What does this print?
vals, target = [6, 7, 9, 1, 3, 4], 3
lo, hi = 0, len(vals) - 1
seen = []
while lo <= hi:
mid = (lo + hi) // 2
seen.append(vals[mid])
if vals[mid] == target:
break
if vals[lo] <= vals[mid]:
if vals[lo] <= target < vals[mid]:
hi = mid - 1
else:
lo = mid + 1
elif vals[mid] < target <= vals[hi]:
lo = mid + 1
else:
hi = mid - 1
print(seen)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [9, 3]
Right: the left half [6, 7, 9] is sorted and 3 is not in it, so the search jumps right and finds 3.
Checking which half is sorted lets the search discard half the list even across the rotation.
Why not the others?
- B [9, 1, 3]. After 9 the range is [1, 3, 4], whose middle is 3.
- C [1, 3]. The first middle index is 2, which holds 9.