I implemented this peak finder for practice. I have tested it. Everything looks pretty good to me. Please let me know if there is any improvement I can make.
Peak Finder
Let input be an array.
input[i]
is a peak ifinput[i] >= input[i + 1]
andinput[i] >= input[i - 1]
.Implement a recursive algorithm of time complexity \$O(\log{n})\$ to find a peak.
class PeakFinder <E extends Comparable<? super E>>{
private E[] array;
public PeakFinder(E[] array){
if(array == null || array.length == 0)
throw new IllegalArgumentException("array cannot be null or 0");
this.array = array;
}
public E find(){
return findUtil(0, array.length - 1);
}
private E findUtil(int left, int right){
int mid = (right - left)/2 + left;
int newLeft = mid + 1;
int newRight = mid - 1;
if(newLeft <= right && array[newLeft].compareTo(array[mid]) > 0)
return findUtil(newLeft, right);
else if(newRight >= left && array[newRight].compareTo(array[mid]) > 0)
return findUtil(left, newRight);
else
return array[mid];
}
}
An array always has at least one peak if it is not null or empty.
Special cases:
input[i]
is a peak ifinput[i] >= input[i+1]
wheninput[i]
is the first element in the array.input[i]
is a peak ifinput[i] >= input[i-1]
wheninput[i]
is the last element in the array.input[i]
is a peak ifinput[i]
is the only element in the array.