Created
November 9, 2017 07:45
-
-
Save escray/b92bb2dba46873eb2b7f3acbcf69a42a to your computer and use it in GitHub Desktop.
binary search
This file contains hidden or 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
def binary_search(arr, element) | |
arr.sort! | |
i = 0 | |
j = arr.length - 1 | |
puts binary(arr, i, j, element) | |
end | |
def binary(arr, i, j, element) | |
mid = (i + j) / 2 | |
if element < arr[mid] | |
return binary(arr, i, mid - 1, element) | |
elsif element > arr[mid] | |
return binary(arr, mid + 1, j, element) | |
else | |
return mid | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment