Am I one of the 10% of programmers who can write a binary search?
I think I might be! After reading an article claiming that only 10% of programmers can write a binary search I decided to give it a shot. After about 20 minutes, I came up with this:
def bsearch(array, search, start_ix=0, end_ix=array.length)
mid_ix = start_ix + ((end_ix-start_ix)/2).ceil
if array[mid_ix] == search then
puts "%d found at position %d" % [ search, mid_ix]
elsif start_ix == mid_ix then
puts "%d not found" % [ search ]
elsif array[mid_ix] < search
bsearch(array, search, mid_ix, end_ix)
elsif array[mid_ix] > search then
bsearch(array, search, start_ix, mid_ix)
end
end
bsearch([10, 20, 30, 40, 50, 60, 70, 80, 90], ARGV[0].to_i)
It’s probably not by best work, and I’m pretty doubtful that I could have done it in the same amount of time under the stress of a job interview. But it works, and that’s good enough for me, considering that I haven’t been a full time programmer in quite some time and haven’t written anything like this since college. ;-)
April 19, 2010