Hi All,
I just finished the codeacademy Ruby course, and ventured to
write a binary search in Ruby.
After years of Java , this is fun !
Let me know what you think - any feedback / tips / pointers , alternate
ways of doing the same - are welcome !!
######################################################
binary search implementation
def bsearch(a,y)
#puts " – >> #{a} #{a.length} find #{32}"
return false if a == nil
return false if a.length == 0
return false if a.length == 1 && a[0] != y
return true if a.length == 1 && a[0] == y
l = a.length
return true if a[ l/2 ] == y
return bsearch a[ 0,l/2],y if y < a[l/2]
return bsearch a[ l/2, l],y
end
1000.times do |x|
# create an array of 100 random numbers
a = []
100.times{ |x| a.push rand(100) }
a.sort!
# set the number to search for
x = 32
# search using our method
contains_x = bsearch( a, x)
# verify using ruby's built-in include?
check = a.include? x
# print the verdict
puts contains_x == check ? " you win a toaster ! " : " fail! "
end
######################################################