Question 1[14 marks]
A school library looks up books by their ID numbers.
Complete the trace table for this Python code. A school library keeps its book IDs in ids, sorted from smallest to largest. This code is a binary search for the book with ID 150. // divides and keeps only the whole number part, and found stays -1 until the book is found. Then answer the question below the table. [4]
ids = [104, 117, 123, 138, 150, 162, 171]
target = 150
low = 0
high = len(ids) - 1
found = -1
while low <= high and found == -1:
mid = (low + high) // 2
if ids[mid] == target:
found = mid
elif ids[mid] < target:
low = mid + 1
else:
high = mid - 1
How many positions of ids did the loop look at in all, including the one where it found 150?
A school library gives every book a whole-number ID. The IDs are kept in a list (an array in Java) called ids, sorted from smallest to largest, with no ID appearing twice.
Write a function that uses a binary search to return the position (the index) of target in ids, or -1 if no book has that ID. Positions start at 0.
- Keep two positions,
lowandhigh, for the part of the list that could still holdtarget. They start at the first and the last position. - Look at the middle position,
(low + high)divided by 2, rounded down. If the ID there istarget, return that position. If it is smaller thantarget, search only the part after it; if it is larger, search only the part before it. - When
lowhas passedhigh, nothing is left to search, so return-1. idscan be empty, and holds at most 10000 IDs, each between 1 and 1000000.- Write the search yourself. The shortcuts listed with this question are not allowed.
The tests check only the number your function returns, so they cannot tell a binary search from a linear one. In the exam, a linear search would not earn the marks for this part.
def find_book(ids: list[int], target: int) -> int
public static int findBook(int[] ids, int target)
A Paper 2 question that asks for a binary search wants to see the search written out, so the built-in searches are not allowed.
Write it as in the exam, then run the testsPractise it with the Run button
[6]
A school library keeps the IDs of its 1000 books in a list (an array in Java), and a librarian looks up one ID at a time.
(a) Explain why a binary search only works if the IDs are sorted. [2]
(b) State the largest number of IDs a linear search would have to look at to find one ID, and the largest number a binary search would have to look at, for the 1000 books. [2]
[4]