Created
November 12, 2018 12:40
-
-
Save suganya-sangith/05f5aab7970da41410548f85000ccaee to your computer and use it in GitHub Desktop.
Binary search algorithm in Ruby
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
#!/home/suganya/.rvm/rubies/ruby-2.4.1/bin/ruby | |
require "byebug" | |
class BinarySearch | |
def search(arr, element_to_search) | |
if arr.length == 1 | |
return arr[0] == element_to_search ? arr[0] : "No match found" | |
else | |
mid_element_index = middle_element(arr) | |
mid_element = arr[mid_element_index] | |
if element_to_search < mid_element | |
arr = arr[0..mid_element_index-1] | |
elsif element_to_search > mid_element | |
arr = arr[mid_element_index+1..arr.length] | |
elsif mid_element == element_to_search | |
return mid_element | |
end | |
search(arr, element_to_search) | |
end | |
end | |
def middle_element(arr) | |
arr_size = arr.size.to_f / 2 | |
arr_size.ceil | |
end | |
end | |
array = [2,5,8,12,16,23,38,56,72,91] | |
element_to_search = 38 | |
result = BinarySearch.new.search(array, element_to_search) | |
puts result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment