DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Largest no. in Array using Recursion
Mysterio
Mysterio

Posted on

Largest no. in Array using Recursion

Hello guys today i want to show you how to find largest number in array using recursion.
Well i found this question today and then searched the stackoverflowπŸ˜‚ and found this solution and then tried to understand this solution.
Lets get started...

Code -

const findMax = arr => {
  if (!Array.isArray(arr)) throw 'Not an array'
  if (arr.length === 0) return undefined
  const [head, ...tail] = arr
  if (arr.length === 1) return head
  return head > findMax(tail) 
    ? head
    : findMax(tail)
}

console.log(findMax([1,9,10,28,78,10]))
Enter fullscreen mode Exit fullscreen mode

Working -

  • First we will check that the argument passed is an arrow or not , if it is not an array then throw an error
  • Then we will check if the length of array is 0 , if it is , return undefined.
  • In the next line , we destructured the array in two parts - head and tail, head containes the first element of the array and ...tail contains the rest of the array
  • After that we check that if the array length is 1 , if it is then we will return the head (the first and only element of that array)
  • Then we used the ternary operator to provide the condition, if the head is greater than findMax(tail) meaning the head element is the first element and findMax(tail) will give the first element from the tail array which is the next element jsut after that , so we will compare those two , if the condition is true , we will return the head element as the largest and if the condition is false then we will recursively check the tail and use the first element of that array as head and the rest as other tail element
  • So, Recursively it will check and compare all the elements in the array and gives us the largest one.

It looks quite confusing and i tried my best to explain and if you find any point wrong please correct it in the comment section.

Easy and Fast approach

const findMax = array => Math.max(...array);
Enter fullscreen mode Exit fullscreen mode

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank youπŸ‘‡πŸ‘‡ ^^
β˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

Top comments (8)

Collapse
frankwisniewski profile image
Frank Wisniewski • Edited on

It is not very helpful to check each call to see if arr is an array, if the array is empty, or if it only has one value.

"use strict";

const findMax = ( arr ) => {
  const fmax = ( arr ) => {
    if ( arr[ idx ] > max ) 
      max = arr[ idx ]
    if ( idx < arr.length ) {
      idx++;
      fmax( arr )
    }
    return max
  }
  if ( !Array.isArray( arr ) ) throw 'Not an array'
  if ( arr.length === 0 ) return undefined
  if ( arr.length === 1 ) return arr[ 0 ]
  let idx = 0
  let max = arr[ idx ]
  max = fmax( arr )
  return max
}
console.log ( findMax ( [ -10,-9 ] ) )
console.log ( findMax ( [ 1,9,100,28,78,10 ] ) )
Enter fullscreen mode Exit fullscreen mode
Collapse
shubhamtiwari909 profile image
Mysterio Author

Yeah for recursion approach it's not good

Collapse
frankwisniewski profile image
Frank Wisniewski

in this case for loop would be more appropriate...

Thread Thread
shubhamtiwari909 profile image
Mysterio Author

Actually it is a question which is asked in an interview so i tried to solve it later because I was not able to solve it at the time of interview πŸ˜‚πŸ˜‚

Thread Thread
fjones profile image
FJones

Okay, yeah, I would've refused that answer with "why on Earth would you do that?".

Thread Thread
shubhamtiwari909 profile image
Mysterio Author

Yeah it won't make a difference Because they already rejected πŸ˜‚πŸ˜‚

Collapse
lukeshiru profile image
Luke Shiru

Worth mentioning for the folks checking the article that if you need to find the max number in an array, this isn't the way to go, but instead just use Math.max like this:

const findMax = array => Math.max(...array);
Enter fullscreen mode Exit fullscreen mode

Is orders of magnitude faster. I get that the idea with the article was to "explore the idea" of doing it recursively, but still is worth mentioning so nobody uses this in "production".

Cheers!

Collapse
shubhamtiwari909 profile image
Mysterio Author

Yeah i should have mentioned this approach also πŸ˜‰

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.