Binary Search Using Lambda

S

Steven Hansen

Greetings,

I've been playing around with various ways to write a function that
does a binary search on an array of integers.
Below is one of my implementations. I'm wondering if it is possible
to avoid passing the function to itself
in order to achieve the recursive call. While I'm defining the
function's body, is there a special syntax to define
a recursive call to the function being defined?

I'm also interested in any feedback folks may have to offer regarding
the below implementation.

Thanks,
Steven



# Attempts to locate "int" in "int_array"
# if "int" is found, this function will return
# the index of "int's" location. If "int" is not
# found, this function will return -1. This function
# assumes that "int_array" is already sorted in
# ascending order.
#
# Example: chop(3, [1, 2, 3, 4, 5]) #=> 2

def chop(int, int_array)
func = lambda { |low, high, int, int_array, f|
return -1 if high < low
mid = low + ((high-low) / 2)

if int < int_array[mid]
high = mid-1
elsif int > int_array[mid]
low = mid+1
else
return mid
end

f.call(low, high, int, int_array, f)
}

func.call(0, int_array.size-1, int, int_array, func)
end
 
L

Logan Capaldo

Greetings,

I've been playing around with various ways to write a function that
does a binary search on an array of integers.
Below is one of my implementations. I'm wondering if it is
possible to avoid passing the function to itself
in order to achieve the recursive call.

You don't need one.

% cat recursion_diversion.rb
func = lambda do |x|
if x == 0
puts "Recursing"
func.call(1)
else
puts "Done"
end
end

func.call( 0 )

% ruby recursion_diversion.rb
Recursing
Done
 
S

Steven Hansen

You don't need one.

% cat recursion_diversion.rb
func = lambda do |x|
if x == 0
puts "Recursing"
func.call(1)
else
puts "Done"
end
end

func.call( 0 )

% ruby recursion_diversion.rb
Recursing
Done


Cool, thanks Logan.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
VetaMcRae
Top