I am writing the code for peak finding algorithm for a 1D array. I have read this post Peak finding algorithm. This is exactly what I am trying to do, there is discussion about time complexity but nothing of sort of pseudocode. The problem:
Given an array
[a,b,c,d,e,f,g]
wherea
tog
are numbers,b
is a peak if and only ifa<=b
andb>=c
.
Example: given an array {1,2,3,4,5,19,25,20}
, index 6
should be returned.
The edge cases should give:
{100,4,3,1,19,20} -- index 0
{1,3,5,19,20} -- index 4
I have implemented in Java
. my current run-time is O(n)
. I am wondering if this could be improved
public static int naive(int[] arr){
int l=arr.length;
if (arr[0]>=arr[1]) {
return 0;
}
if (arr[l-1]>arr[l-2]){
return l-1;
}
for (int i=1; i < arr.length-1;i++){
if (arr[i] >= arr[i-1] && arr[i] >= arr[i+1] ){
return i;
}
}
return -1;
}