2010-01-17 16:18:24 -05:00
|
|
|
# Beautiful Code, Chapter 6.
|
|
|
|
# The implementation of binary search that is tested.
|
|
|
|
|
|
|
|
# Return the index of an element in a sorted list. (or -1, if not present)
|
2010-07-29 00:03:42 -04:00
|
|
|
index = (list, target) ->
|
|
|
|
[low, high] = [0, list.length]
|
2010-01-17 16:18:24 -05:00
|
|
|
while low < high
|
2010-07-29 00:03:42 -04:00
|
|
|
mid = (low + high) >> 1
|
|
|
|
val = list[mid]
|
2010-01-17 16:18:24 -05:00
|
|
|
return mid if val is target
|
2010-07-29 00:03:42 -04:00
|
|
|
if val < target then low = mid + 1 else high = mid
|
2010-01-17 16:18:24 -05:00
|
|
|
return -1
|
|
|
|
|
2010-10-24 12:48:42 -04:00
|
|
|
console.log 2 is index [10, 20, 30, 40, 50], 30
|
|
|
|
console.log 4 is index [-97, 35, 67, 88, 1200], 1200
|
|
|
|
console.log 0 is index [0, 45, 70], 0
|