In: Computer Science
An array A of n distinct numbers are said to be unimodal if there exists an index k, 1 ≤ k ≤ n, such that A[1] < A[2] < · · · < A[k − 1] < A[k] and A[k] > A[k + 1] > · · · > A[n]. In other words, A has a unique peak and are monotone on both sides of the peak. Design an efficient algorithm that finds the peak in a unimodal array of size n.
Answer : Given data
* Unimodal if there exists an index k, 1 ≤ k ≤ n, such that A[1] < A[2] < · · · < A[k − 1] < A[k] and A[k] > A[k + 1] > · · · > A[n].
public int findPeak(int[] arr, int low, int high){
if(low == high - 1){
return
arr[low];
}
int mid = low + (high - low) /
2;
if(arr[mid] < arr[mid +
1]){
return
findPeak(arr, mid + 1, high);
} else{
return
findPeak(arr, low, mid - 1);
}
}
*You can call this method from the main method as follows : findPeak(arr, 0, n - 1)
*where n is the length of the array.
*What we are essentially doing is the reducing our search space in the array to half after each recursive call until we meet our base condition.
______________THE END__________________