Created
April 21, 2010 10:20
-
-
Save kgthegreat/373661 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(sorted_array, number_to_be_searched) | |
size = sorted_array.size | |
if number_to_be_searched < sorted_array[0] || number_to_be_searched > sorted_array[size-1] | |
puts "Number not found" | |
return | |
end | |
middle_index = size/2 | |
middle_element = sorted_array[middle_index] | |
if middle_element === number_to_be_searched | |
middle_index = middle_index/2 | |
puts "the position of the sought number is #{size}" | |
return | |
elsif middle_element > number_to_be_searched | |
sorted_array = sorted_array.slice(0,middle_index) | |
elsif middle_element < number_to_be_searched | |
sorted_array = sorted_array.slice(middle_index,size) | |
end | |
binary_search(sorted_array, number_to_be_searched) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment