How to use Recursion In Javascript
- Create a recursive function.
- Set an integer i = 0 to denote the current index being searched.
- Return steps 4 to 7 to get the final answer.
- If i is the last index, return arr[i].
- Increment i and call the recursive function for the new value of i.
- Compare the maximum value returned from the recursion function with arr[i].
- Return the max between these two from the current recursion call.
Example:
// JS program to find maximum
// in arr[] of size n
function largest(arr, n, i) {
// last index
// return the element
if (i == n - 1) {
return arr[i];
}
// find the maximum from rest of the array
let recMax = largest(arr, n, i + 1);
// compare with i-th element and return
return Math.max(recMax, arr[i]);
}
// Driver Code
const arr = [22, 65, 1, 39];
const n = arr.length;
console.log("Largest in given array is", largest(arr, n, 0));
Output
Largest in given array is 65
Javascript Program to Find the Largest Element in an Array
Finding the largest element in an array is a common task in JavaScript, useful in various scenarios such as data analysis, sorting, and mathematical computations. This article explores several methods to efficiently determine the largest element, ensuring robust and optimized solutions for your coding needs. Let’s first see simple examples input and output.
Examples:
Input: arr = [10, 20, 4]
Output: 20
Explanation: Among 10, 20 and 4, 20 is the largest.Input : arr = [20, 10, 20, 4, 100]
Output : 100
Contact Us