Skip to content

Instantly share code, notes, and snippets.

@yclim95
Created January 13, 2016 09:20
Show Gist options
  • Save yclim95/9931a5e5e077a3f54ec5 to your computer and use it in GitHub Desktop.
Save yclim95/9931a5e5e077a3f54ec5 to your computer and use it in GitHub Desktop.
#1.0 takes in the number and a array of number
# 1.1 sort the array of number
# 1.2 check if is lower || higher (array.size)
# 1.3 keep dividing it into half each time until -1
# 1.4 Once stop get the index of the place u stop
def sort_array(array_num)
array_num.sort!
end
def binary_search(num, array_num, lowest_size=0, highest_size=array_num.length-1)
sort_array(array_num)
return -1 if lowest_size > highest_size
middle_value=(lowest_size+highest_size)/2
return middle_value if array_num[middle_value]==num # return the position if it is == to the arrayNum
if array_num[middle_value] < num
lowest_size=middle_value+1
else
highest_size=middle_value-1
end
puts binary_search(num,array_num,lowest_size,highest_size)
end
binary_search(44, [13, 19, 24, 29, 32, 37, 43])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment