/examples/beautiful_code/binary_search.coffee
CoffeeScript | 16 lines | 11 code | 2 blank | 3 comment | 4 complexity | 73fff5ea64ff0f5dcf590da23dc142e1 MD5 | raw file
1# Beautiful Code, Chapter 6. 2# The implementation of binary search that is tested. 3 4# Return the index of an element in a sorted list. (or -1, if not present) 5index = (list, target) -> 6 [low, high] = [0, list.length] 7 while low < high 8 mid = (low + high) >> 1 9 val = list[mid] 10 return mid if val is target 11 if val < target then low = mid + 1 else high = mid 12 return -1 13 14console.log 2 is index [10, 20, 30, 40, 50], 30 15console.log 4 is index [-97, 35, 67, 88, 1200], 1200 16console.log 0 is index [0, 45, 70], 0