dcf.cymru stimulus sheet · Computer Science · Year 11

Search algorithm reference sheet

One sorted list, two correct algorithms and one broken one. The list is invented: 16 book ID numbers from one shelf of a school library, already sorted into ascending order.

The list

The list is called list and it is zero-indexed: the first item is list[0] and the last is list[15]. LENGTH(list) is 16.

Index 01234567 89101112131415
Value 49152126333842 4755616872808693

Rules for tracing

Linear search

1 FUNCTION linearSearch(list, target) 2 FOR i ← 0 TO LENGTH(list) − 1 3 IF list[i] = target THEN 4 RETURN i 5 ENDIF 6 NEXT i 7 RETURN −1 8 ENDFUNCTION

Checks every item in turn from the front. It works on any list, sorted or not.

Binary search — Version A (correct)

1 FUNCTION binarySearch(list, target) 2 low ← 0 3 high ← LENGTH(list) − 1 4 WHILE low <= high 5 mid ← (low + high) DIV 2 6 IF list[mid] = target THEN 7 RETURN mid 8 ELSE IF list[mid] < target THEN 9 low ← mid + 1 10 ELSE 11 high ← mid − 1 12 ENDIF 13 ENDWHILE 14 RETURN −1 15 ENDFUNCTION

Looks at the middle item of the part of the list still in play, then throws away the half that cannot contain the target. It only works if the list is sorted.

Binary search — Version B (contains one logic error)

1 FUNCTION binarySearchB(list, target) 2 low ← 0 3 high ← LENGTH(list) − 1 4 WHILE low < high 5 mid ← (low + high) DIV 2 6 IF list[mid] = target THEN 7 RETURN mid 8 ELSE IF list[mid] < target THEN 9 low ← mid + 1 10 ELSE 11 high ← mid − 1 12 ENDIF 13 ENDWHILE 14 RETURN −1 15 ENDFUNCTION

Version B differs from Version A by one character. It still finds some items, which is exactly why this kind of error survives into real programs.

An unsorted list, for Step 6

Index 0123456
Value 3012557411960