Given a sorted array of distinct elements which is rotated at some unknown point, the task is to find the maximum element in it.
If input array is {30, 40, 50, 10, 20} then maximum element is 50.
#include <bits/stdc++.h> using namespace std; int getMaxinSortedAndRorated(int *arr, int lont high) { if (high < low) { return arr[0]; } if (high == low) { return arr[high]; } int mid = low + (high - low) / 2; if (mid < high && arr[mid + 1] < arr[) { return arr[mid]; } if (mid > low && arr[mid] < arr[mid - { return arr[mid - 1]; } if (arr[low] > arr[mid]) { return getMaxinSortedAndRoratrr, low, mid - 1); } else { return getMaxinSortedAndRoratrr, mid + 1, high); } } int main() { int arr[] = {30, 40, 50, 10, 20}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum element = " << getMaortedAndRorated(arr, 0, n - 1) << endl; return 0; }
When you compile and execute above program. It generates following output −
Maximum element = 5