Home >Web Front-end >JS Tutorial >Find the peak of an array of central peaks in JavaScript

Find the peak of an array of central peaks in JavaScript

WBOY
WBOYforward
2023-08-24 12:21:07874browse

在 JavaScript 中查找中心峰值数组的峰值

Center Peak Array

If the following properties are satisfied, we call the array arr Center Peak Array -

  • arr.length >= 3

  • There are some i and 0

    • arr[0]

    • arr[ i] > arr[i 1] > .. . > arr[arr.length - 1]

Question

We need to write a JavaScript function that accepts a numeric array arr as the first One and only parameter.

The input array is a center peak array. Our function should return the peak index of this central peak array.

For example, if the input to the function is

input

const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];

output

const output = 4;

Output Explanation

Because the element at index 4 (15) is the peak element of the array.

Example

The following is the code -

Live demonstration

const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];
const findPeak = (arr = []) => {
   if(arr.length < 3) {
      return -1
   }
   const helper = (low, high) => {
      if(low > high) {
         return -1
      }
      const middle = Math.floor((low + high) / 2)
      if(arr[middle] <= arr[middle + 1]) {
         return helper(middle + 1, high)
      }
      if(arr[middle] <= arr[middle - 1]) {
         return helper(low, middle - 1)
      }
      return middle
   }
   return helper(0, arr.length - 1)
};
console.log(findPeak(arr));

Output

4

The above is the detailed content of Find the peak of an array of central peaks in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete