Last active
July 7, 2017 17:41
-
-
Save ashlinchak/9a6f901866665e72495a20e10152b3af to your computer and use it in GitHub Desktop.
Binary Search.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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