Subpar Web Dev
Subpar Web Dev

Reputation: 3260

Where is the flaw in my algorithm for finding the max element of an array?

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?

Upvotes: 0

Views: 78

Answers (1)

Salvador Dali
Salvador Dali

Reputation: 222461

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.

Upvotes: 1

Related Questions