I am writing code for the peak search algorithm for a 1D array. I read this post Peak Search Algorithm . This is exactly what I'm trying to do, there is a discussion about time complexity, but nothing like pseudo code. Problem:
Given an array [a,b,c,d,e,f,g]where a- gare numbers, bis a peak if and only if a<=band b>=c.
Example: Given an array {1,2,3,4,5,19,25,20}, an index should be returned 6. The edges should give:
{100,4,3,1,19,20} -- index 0
{1,3,5,19,20} -- index 4
I implemented in Java. current runtime O(n). I wonder if this can 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;
}
source
share