Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamal-github/af34c30085de5ffdc5755e71523613b5 to your computer and use it in GitHub Desktop.
Save kamal-github/af34c30085de5ffdc5755e71523613b5 to your computer and use it in GitHub Desktop.
#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