December
1999 QUESTION 5 Total Marks: 15 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS |
(a) |
Briefly describe the Binary Search algorithm. A binary search works by •Comparing the value in the middle of the list with the key, and sub dividing this search to the lower half if it is greater, or the upper half if it is less,(1 mark) •Until the element is found, or the list cannot be further sub-divided. (1 mark)
|
[2] |
(b) |
State the worst case number of comparisons needed to perform a complete Binary Search on a list of size N. At most,
|
[1] |
(c) |
Given the sorted list x below, show how the positions of the indicators Left (L ),Right (R )and Middle (M )evolve during a binary search for the number 23.
Each stage should be represented as the following: •Stage 1:L =5, R =100, M =17 (1 mark) •Stage 2:L =23, R =100, M =17 (1 mark) •Stage 3:L =23, R =100, M =50 (1 mark) •Stage 4:L =23, R =23, M =50 (1 mark) •Stage 5:L =23, R =23, M =23 (1 mark)
|
[5] |
(d) |
Write a function BSearch, the signature
of which is given below, which takes a sorted list x of type ListType,
a integer y specifying the length of the list, and a search term z
of type ListElement, which is the type of data held in the list, and
searches the list for the search term using the binary search algorithm.The
function should return the position of the item in the list if it
is present, or -1 otherwise. In your function, you can use the list
interface function DataAt, the signature of which is also given below,
which will return the value of the data item stored at position y
in the list
A sample definition of BSearch follows:
Declaring a loop which is bound by the inequality of High and Low ;(1 mark) Setting Mid to the middle value on each iteration;(1 mark) Comparing
the value at the current Mid of the list using DataAt Returning Mid if it is equal to the search term;(1 mark) Reassigning High or Low based on the comparison with the current term;(1 mark) Returning -1 if the whole list has been searched without a successful match; (1 mark) |
[7] |