Created
March 27, 2017 16:14
-
-
Save kamal-github/af34c30085de5ffdc5755e71523613b5 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
#ex array | |
a = [3,4,5,1,2] | |
pivot = -1 | |
(0..a.length-1).each do |i| | |
if a[i] > a[i+1] | |
pivot = i+1 | |
break | |
end | |
end | |
def bsearch(a, i, j, n) | |
mid = (i + j)/2 | |
if i == j and n != a[mid] | |
return -1 | |
end | |
if n == a[mid] | |
return mid | |
elsif n < a[mid] | |
return bsearch(a, i, mid, n) | |
elsif n > a[mid] | |
return bsearch(a, mid+1, j, n) | |
end | |
end | |
#Client code | |
x = bsearch(a[0..pivot-1], 0, pivot-1, 2) | |
y = bsearch(a[pivot..a.length-1], 0, a.length-1-pivot, 2) | |
if x != -1 | |
puts "Found #{x}" | |
elsif y != -1 | |
puts "Found #{y+pivot}" | |
else | |
put "NOT Found" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment