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
Release: 2023-08-24 12:21:07
forward
869 people have browsed it

在 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];
Copy after login

output

const output = 4;
Copy after login

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));
Copy after login

Output

4
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template