Last active
April 14, 2017 13:57
-
-
Save alovak/474598ae6e5193b7008f3abe4ef31489 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
a = (1..100).to_a.rotate 7 | |
x = 2 | |
steps = 0 | |
n = 0 | |
l = 0 | |
r = a.length | |
while true do | |
steps+=1 | |
m = (r-l+1) / 2 | |
n = l + m | |
break if a[n] == x | |
(n = l; break) if a[l] == x | |
(n = r; break) if a[r] == x | |
if (a[l] < a[n]) && (a[l] < x && a[n] > x) | |
r = n | |
elsif (a[l] > a[n]) && (a[l] < x || x < a[n]) | |
r = n | |
else | |
l = n | |
end | |
break if steps > 20 | |
end | |
puts "#{x} is N #{n} (start from 0) in" | |
puts a.inspect | |
puts "found in #{steps} steps" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment