Simple Recursion in Javascript with/without a subroutine -
i'm stuck on how find max value of array recursively in javascript. tried first iteratively , of course works. recursively, wanted try subroutine first, , without subroutine. what's best way call subroutine inside itself? getting tripped want inside indices, subroutine accepts array parameter.
function maxvalue(arr) { var max = 0; (var = 0; < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } console.log(maxvalue([2, 7, 8, 3, 1, 4])); //returns 8 function maxvaluerecursive(arr) { var length = arr.length; //6 var max = 0; function dosearch(arr) { if (arr.length === 1) { max = arr[0]; } else { // true max = math.max(arr[length - 1], arr[length - 2]); //max = math.max(4, dosearch()) = 4. } return max; } return dosearch(arr); } console.log(maxvaluerecursive([2, 7, 8, 3, 1, 4])) //returns 4
you can use math.max
, solve smaller bit of array @ each step. trick remove (any) item array , use math.max
compare item findmax
on smaller array:
function findmax(arr){ if (arr.length == 1){ // base case - single item in array max return arr[0]; } // recursive call on smaller problem (shorter array) return math.max(arr[0], findmax(arr.slice(1))) }
i used slice
can use pop
or whatever method remove item , compare using math.max
did.
for array [1, 4, 2, 3]
recursion unfolds follows:
1. findmax([1, 4, 2, 3] 2. math.max(1, findmax([4, 2, 3])) 3. math.max(1, math.max(4, findmax([2, 3]))) 4. math.max(1, math.max(4, math.max(2, findmax([3])))) 5. math.max(1, math.max(4, math.max(2, 3))) // 4
Comments
Post a Comment