Created
May 10, 2016 19:00
-
-
Save shtakai/dc933be0d5e9027ce1c1b25c9dafef8d to your computer and use it in GitHub Desktop.
binary search 2016/05/10
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
require 'pp' | |
def search(a, t) | |
#pp "a:#{a} t:#{t}" | |
return a[0] if a.size == 1 | |
middle_index = (a.size/2).to_i | |
#pp "m:#{middle_index} a[m]:#{a[middle_index]}" | |
t < a[middle_index] ? search(a[0..middle_index-1],t) : search(a[middle_index..a.size], t) | |
end | |
#list = [1,2,3,4,5,6,7,555,6700] | |
list = (500..600).to_a | |
pp list | |
target = 555 | |
pp search(list,target) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment