ExamBank Scot · AH Computing Science question bank · All AH Computing Science questions

AH Computing Science 2022 Question 2

3 marks · Binary search

A binary search algorithm is shown below. This algorithm is incomplete. 1. Set low = 0 2. Set high = number of elements in the list − 1 3. Set found = false 4. While ________________________ 5. Set mid = (low + high) / 2 6. If target = list[mid] then 7. Set position = mid 8. Set found = true 9. Else if _____________________ 10. Set low = mid + 1 11. Else 12. Set high = mid − 1 13. End if 14. End while Write the conditions needed to complete line 4 and line 9 of the algorithm. The contents of an array are shown below. 49366323 35888744 35332982 51087533 35471544 63728272 35395841 35646683 35853694 35676309 35666839 Explain why the binary search algorithm would not return the expected result when applied to the array.

Marking scheme

Line 4: not found and low <= high Line 9: target > list[mid] 1 mark for each correct condition Also accept: Line 4: not found and high >= low Line 9: list[mid] < target The contents of the array are unsorted.

Previous question: AH Computing Science 2022 Question 1

Next question: AH Computing Science 2022 Question 3