Skip to content

Instantly share code, notes, and snippets.

@kgthegreat
Created April 21, 2010 10:20
Show Gist options
  • Save kgthegreat/373661 to your computer and use it in GitHub Desktop.
Save kgthegreat/373661 to your computer and use it in GitHub Desktop.
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