Skip to content

Instantly share code, notes, and snippets.

@xsurge83
Created July 14, 2013 03:11
Show Gist options
  • Save xsurge83/5993045 to your computer and use it in GitHub Desktop.
Save xsurge83/5993045 to your computer and use it in GitHub Desktop.
BinarySearch
array = [1,4,5,6,10,13]
class BinarySearch
constructor:(@elems)->
@len = @elems.length
midPoint = (start, end)->
((end - start)/2) + start
find : (value, start=0, end =-1)->
end = @len if end is -1
console.log 'start %s end %s', start, end
if end < start
return null
else
mid = midPoint start, end
console.log 'elems[%s] = %s', mid , @elems[mid]
if mid is @len or mid is 0
return null
if @elems[mid] > value
console.log 'go left'
return @find(value, start, mid - 1)
else if @elems[mid] < value
console.log 'go right'
return @find( value, mid + 1, end)
else
mid
result = new BinarySearch(array).find(4)
console.log 'done'
console.log 'results %s', result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment