Approach: A simple solution is to traverse the complete array and find maximum. This solution requires O(n) time. We can do it in O(Logn) using Binary Search. If we take a closer look at above examples, we can easily figure out the following pattern:
The maximum element is the only element whose next is smaller than it. If there is no next smaller element, then there is no rotation (last element is the maximum). We check this condition for middle element by comparing it with elements at mid – 1 and mid + 1.
If maximum element is not at middle (neither mid nor mid + 1), then maximum element lies in either left half or right half.
If middle element is greater than the last element, then the maximum element lies in the left half.
Else maximum element lies in the right half.
Below is the implementation of the above approach:
// Function to return the maximum element
intfindMax(intarr, intlow, inthigh)
if(high == low)
// Find mid
intmid = low + (high - low) / 2;
// Check if mid reaches 0 ,it is greater than next element or not
Please Login to comment...