Skip to content

Instantly share code, notes, and snippets.

@kenmazaika
Created March 7, 2016 20:16
Show Gist options
  • Save kenmazaika/72ed4fb7a8db372b78c0 to your computer and use it in GitHub Desktop.
Save kenmazaika/72ed4fb7a8db372b78c0 to your computer and use it in GitHub Desktop.
def binary_search(target, list)
# find the middle position number
position = (list.count / 2).floor
# look up the item in the middle position
mid = list[position]
# if we've found it, we're done
return mid if mid == target
if(mid < target)
# mid is less than the target meaning we should continue the process
# on the right half, meaning starting at the position + 1 to the end
# of the list
return binary_search(target, list.slice(position + 1, list.count/2))
else
# mid is greater than the target, meaning we should start
# at the beginning of the list, and eliminate the stuff
# on the right hand side.
return binary_search(target, list.slice(0, list.count/2))
end
end
puts binary_search(9, [1,2,3,4,5,6,7,8,9,10])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment