Skip to content

Instantly share code, notes, and snippets.

@rtacconi
Last active August 7, 2016 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtacconi/7b4387e3e02bee4c4594dfdc2d002099 to your computer and use it in GitHub Desktop.
Save rtacconi/7b4387e3e02bee4c4594dfdc2d002099 to your computer and use it in GitHub Desktop.
Binary search
def binary_search(list, item)
low = 0
high = list.size - 1
return nil if list.last < item # item not in array
while low < high do
mid = (low + high) / 2
guess = list[mid]
if guess == item
return mid
elsif guess > item
high = mid - 1
else
high = mid + 1
end
end
# while terminated without finding anything
return nil
end
p binary_search([1,3,4,6,100], 4)
p binary_search([1,3,4,6,100], 400)
p binary_search(['f', 'g', 'h', 'i'], 'h')
p binary_search(['fa', 'ga', 'ha', 'ia'], 'ia')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment