forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalMaximomPoint.js
More file actions
Latest commit
30 lines (27 loc) · 1.29 KB
/
Copy pathLocalMaximomPoint.js
File metadata and controls
30 lines (27 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* [LocalMaxima](https://www.geeksforgeeks.org/find-indices-of-all-local-maxima-and-local-minima-in-an-array/) is an algorithm to find relative bigger numbers compared to their neighbors
*
* Notes:
* - works by using divide and conquer
* - the function gets the array A with n Real numbers and returns the local max point index (if more than one exists return the first one)
*
* @complexity: O(log(n)) (on average )
* @complexity: O(log(n)) (worst case)
* @flow
*/
constfindMaxPointIndex=(array,rangeStartIndex,rangeEndIndex,originalLength)=>{
// find index range middle point
constmiddleIndex=rangeStartIndex+parseInt((rangeEndIndex-rangeStartIndex)/2)
// handle array bounds
if((middleIndex===0||array[middleIndex-1]<=array[middleIndex])&&
(middleIndex===originalLength-1||array[middleIndex+1]<=array[middleIndex])){
returnmiddleIndex
}elseif(middleIndex>0&&array[middleIndex-1]>array[middleIndex]){
returnfindMaxPointIndex(array,rangeStartIndex,(middleIndex-1),originalLength)
}else{
// regular local max
returnfindMaxPointIndex(array,(middleIndex+1),rangeEndIndex,originalLength)
}
}
constLocalMaximomPoint=(A)=>findMaxPointIndex(A,0,A.length-1,A.length)
export{LocalMaximomPoint}