Skip to content

Instantly share code, notes, and snippets.

@adamloo85
Created November 14, 2013 06:55
Show Gist options
  • Save adamloo85/7462570 to your computer and use it in GitHub Desktop.
Save adamloo85/7462570 to your computer and use it in GitHub Desktop.
Binary search method that searches through a passed array. Takes two parameters, number to be searched and data array.
def binary_search(num, arr)
high = arr.length - 1
low = 0
while low < high
mid = (low + high) / 2
if arr[mid] > num
low = mid + 1
elsif arr[mid] < num
high = mid - 1
elsif arr[mid] == num
return mid
end
end
return -1 if low == high
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment