Skip to content

Instantly share code, notes, and snippets.

@Bablzz
Last active October 27, 2020 16:10
Show Gist options
  • Select an option

  • Save Bablzz/249a390775f7506f87bfadb189193df0 to your computer and use it in GitHub Desktop.

Select an option

Save Bablzz/249a390775f7506f87bfadb189193df0 to your computer and use it in GitHub Desktop.
binary search
# Best O(1)
# Worst O(long n)
arr = [1,2,3,4,5,6,7,10]
def bs (list, elem)
low = 0
high = list.length
while low != high
mid = (low + high) / 2
if elem == list[mid]
puts "Find elem and its number in array #{mid} and equal #{list[mid]}"
return mid
elsif elem < list[mid]
high = mid
else
low = mid + 1
end
end
return -1
end
puts bs(arr, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment