Last active
April 25, 2019 10:15
-
-
Save KevinSia/c04a61858af4a1cfe0a7aaf9556a71a2 to your computer and use it in GitHub Desktop.
This file contains 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
# Place your solutions here | |
# Implement a method named binary_search | |
def binary_search(target, arr) | |
s = 0 | |
e = arr.length - 1 | |
until s < e | |
m = (s + e) / 2 | |
# found target | |
if target == arr[m] | |
return m | |
# target is on left side of the midpoint (set ending point to midpoint) | |
elsif target < arr[m] | |
e = m - 1 | |
# target is on right side of the midpoint (set starting point to midpoint) | |
else | |
s = m + 1 | |
end | |
end | |
return nil | |
end | |
p binary_search(201, (1..200).to_a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment