Skip to content

Instantly share code, notes, and snippets.

@KevinSia
Last active April 25, 2019 10:15
Show Gist options
  • Save KevinSia/c04a61858af4a1cfe0a7aaf9556a71a2 to your computer and use it in GitHub Desktop.
Save KevinSia/c04a61858af4a1cfe0a7aaf9556a71a2 to your computer and use it in GitHub Desktop.
# 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