code_binary_search.coffee 532 B

123456789101112131415161718
  1. # Uses a binary search algorithm to locate a value in the specified array.
  2. window.binary_search = (items, value) ->
  3. start = 0
  4. stop = items.length - 1
  5. pivot = Math.floor (start + stop) / 2
  6. while items[pivot] isnt value and start < stop
  7. # Adjust the search area.
  8. stop = pivot - 1 if value < items[pivot]
  9. start = pivot + 1 if value > items[pivot]
  10. # Recalculate the pivot.
  11. pivot = Math.floor (stop + start) / 2
  12. # Make sure we've found the correct value.
  13. if items[pivot] is value then pivot else -1