In order to feel smarter, I'm trying to write every algorithm recursively, even when a non-recursive solution is more readable and efficient (as in the case of "Hello, World!" hehe). I'm starting out by doing this with a simple max function
function max ( arr )
{
max_in_bounds(arr,0,arr.length);
}
function max_in_bounds ( A, i, j )
{
// finds the max element in the range of
// indices [i, j) of the array A
var diff = j - i;
if ( diff === 1)
{
return A[i];
}
else if ( diff > 1 )
{
return Math.max(A[i], max_in_bounds(A,i+1,A.length));
}
}
var my_array = [1, 4, -3, 69];
console.log(max(my_array)); // Should print 69
but for some reason I'm getting undefined
and I'm trying to figure out why. Any hints?
There is no return in the function:
function max ( arr ){
return max_in_bounds(arr,0,arr.length);
}
and therefore it returns undefined
. Also I hope you are writing these every recursion algorithms only for the learning purposes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.