@@ -5,14 +5,15 @@ Question:
55
66The following search function finds the index of the first occurrence of
77elt in a sorted list lst (or -1 if elt not found). Optimize this
8- function so that it works on a 64-element sorted list by executing less
9- than 50 instructions.
8+ function so that it works on any 64-element sorted list by executing
9+ less than 50 instructions.
1010
1111Hint:
1212Linear search will never work.
1313
1414Solution:
15- Implement binary search instead of linear search.
15+ Implement binary search instead of linear search. A recursive solution
16+ might not be efficient enough, though!
1617
1718MaxInstructions: 50
1819
@@ -26,6 +27,38 @@ def search(lst, elt):
2627 return -1
2728
2829
30+ // # Iterative solution from stackoverflow
31+ // # http://stackoverflow.com/questions/212358/binary-search-in-python
32+ // def search(lst, elt):
33+ // lo, hi = 0, len(lst)
34+ // while lo < hi:
35+ // mid = (lo+hi)//2
36+ // midval = lst[mid]
37+ // if midval < elt:
38+ // lo = mid+1
39+ // elif midval > elt:
40+ // hi = mid
41+ // else:
42+ // return mid
43+ // return -1
44+ //
45+ // # recursive implementation, which is too slow
46+ // def search(lst, elt):
47+ // return bsearch(lst, elt, 0, len(lst))
48+ //
49+ // def bsearch(lst, elt, lo, hi):
50+ // if lo > hi:
51+ // return -1
52+ // mid = (lo+hi)//2
53+ // midval = lst[mid]
54+ // if midval < elt:
55+ // return bsearch(lst, elt, mid+1, hi)
56+ // elif midval > elt:
57+ // return bsearch(lst, elt, lo, mid)
58+ // else:
59+ // return mid
60+
61+
2962Test:
3063haystack = range(64)
3164needle = 63
0 commit comments