* @function findMaxRecursion * @description This algorithm will find the maximum value of a array of numbers. * * @param {Integer[]} arr Array of numbers * @param {Integer} left Index of the first element * @param {Integer} right Index of the last element * * @return {Integer} Maximum value o
(arr, left, right)
| 15 | * @example findMaxRecursion([-1, -2, -4, -5]) = -1 |
| 16 | */ |
| 17 | function findMaxRecursion(arr, left, right) { |
| 18 | const len = arr.length |
| 19 | |
| 20 | if (len === 0 || !arr) { |
| 21 | return undefined |
| 22 | } |
| 23 | |
| 24 | if (left >= len || left < -len || right >= len || right < -len) { |
| 25 | throw new Error('Index out of range') |
| 26 | } |
| 27 | |
| 28 | if (left === right) { |
| 29 | return arr[left] |
| 30 | } |
| 31 | |
| 32 | // n >> m is equivalent to floor(n / pow(2, m)), floor(n / 2) in this case, which is the mid index |
| 33 | const mid = (left + right) >> 1 |
| 34 | |
| 35 | const leftMax = findMaxRecursion(arr, left, mid) |
| 36 | const rightMax = findMaxRecursion(arr, mid + 1, right) |
| 37 | |
| 38 | // Return the maximum |
| 39 | return Math.max(leftMax, rightMax) |
| 40 | } |
| 41 | |
| 42 | export { findMaxRecursion } |
no outgoing calls
no test coverage detected