Created
March 29, 2016 15:36
-
-
Save mindplace/d9bda84fffb63271e967 to your computer and use it in GitHub Desktop.
This file contains 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(array, item) | |
index = nil | |
found = false | |
mid_point = array.length / 2 | |
before = 0 | |
after = 0 | |
while found == false | |
if array.length < 2 || array[mid_point] == item | |
found = true | |
if array.length < 2 | |
index = before + 1 if array[0] == item | |
index = -1 if array[0] != item | |
elsif array[mid_point] == item | |
index = mid_point + before | |
end | |
elsif array[mid_point] > item | |
after += array[mid_point...-1].length | |
array = array[0..mid_point] | |
mid_point = array.length / 2 | |
elsif array[mid_point] < item | |
before += array[0...mid_point].length | |
array = array[mid_point..-1] | |
mid_point = array.length / 2 | |
end | |
end | |
index | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment