Created
May 19, 2018 20:47
-
-
Save sulmanweb/a8887875411c47c3d25eb4e2ca7c0f38 to your computer and use it in GitHub Desktop.
Binary Search
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
# Binary Search Algorithm | |
# Time Complexity = o(log n + 1) | |
# Precondition: List should be sorted | |
class BinarySearch | |
def search_func (array, to_search) | |
low = 0 | |
high = array.length - 1 | |
while low <= high | |
mid = low + ((high - low) / 2) | |
if array[mid] == to_search | |
return mid | |
elsif array[mid] < to_search | |
low = mid + 1 | |
else | |
high = mid - 1 | |
end | |
end | |
return "Value not found in array" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment