Skip to content

Instantly share code, notes, and snippets.

@ashlinchak
Last active July 7, 2017 17:41
Show Gist options
  • Save ashlinchak/9a6f901866665e72495a20e10152b3af to your computer and use it in GitHub Desktop.
Save ashlinchak/9a6f901866665e72495a20e10152b3af to your computer and use it in GitHub Desktop.
Binary Search.
def iterative_binary_search(array, value)
start = 0
top = array.size - 1
while top >= start
middle = (start + top) / 2
if array[middle] == value
return middle
elsif array[middle] > value
top = middle - 1
else
start = middle + 1
end
end
raise StandardError, 'Cannot search. Maybe an array is not sorted or value out of the range of the array?'
end
def recursive_binary_search(array, value, start = 0, top = nil)
top ||= array.length - 1
middle = (start + top) / 2
if start > top
raise StandardError, 'Cannot search. Maybe an array is not sorted or value out of the range of the array?'
end
if array[middle] == value
middle
elsif array[middle] > value
top = middle - 1
recursive_binary_search(array, value, start, top)
else
start = middle + 1
recursive_binary_search(array, value, start, top)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment