Maximum element in a sorted and rotated array in C++

C++Server Side ProgrammingProgramming

Description

Given a sorted array of distinct elements which is rotated at some unknown point, the task is to find the maximum element in it.

Example

If input array is {30, 40, 50, 10, 20} then maximum element is 50.

Algorithm

  • 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 i.e. 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 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

Example

#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;
}

Output

When you compile and execute above program. It generates following output −

Maximum element = 5
raja
Published on 10-Jan-2020 07:01:54
Advertisements