PageRenderTime 21ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/beautiful_code/binary_search.coffee

http://github.com/jashkenas/coffee-script
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. # Return the index of an element in a sorted list. (or -1, if not present)
  4. index = (list, target) ->
  5. [low, high] = [0, list.length]
  6. while low < high
  7. mid = (low + high) >> 1
  8. val = list[mid]
  9. return mid if val is target
  10. if val < target then low = mid + 1 else high = mid
  11. return -1
  12. console.log 2 is index [10, 20, 30, 40, 50], 30
  13. console.log 4 is index [-97, 35, 67, 88, 1200], 1200
  14. console.log 0 is index [0, 45, 70], 0