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
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