Find Minimum in Rotated Sorted Array in C++


Suppose there is an array, and that is sorted, consider that array is rotated at some pivot, that is unknown to us. So we have to find the minimum from that rotated array. So if the array is like [3,4,5,1,2], then the output will be 1.

To solve this, we will follow these steps −

  • low := 0 and high := last index of array, n := size of array, ans := infinity
  • while low <= high
    • mid := low + (high - low)/2
    • if arr[low] < arr[mid], then ans := minimum of ans and arr[low], low := mid + 1
    • else if arr[high] > arr[mid], then ans := minimum of ans and arr[mid], high := mid – 1
    • else if low = mid, then ans := minimum of ans and arr[low], low := mid + 1
    • else if high = mid, then ans := minimum of ans and arr[high], high := mid - 1
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int findMin(vector<int>& arr) {
      int low = 0;
      int high = arr.size() - 1;
      int n = arr.size();
      int ans = INT_MAX;
      while(low <= high){
         int mid = low + (high - low) / 2;
         if(arr[low] < arr[mid]){
            ans = min(ans, arr[low]);
            low = mid + 1;
         } else if(arr[high] > arr[mid]) {
            ans = min(ans, arr[mid]);
            high = mid - 1;
         } else if(low == mid) {
            ans = min(ans, arr[low]);
            low = mid + 1;
         } else if(high == mid) {
            ans = min(ans, arr[high]);
            high = mid - 1;
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {15,35,85,96,5,6,8,12};
   cout << ob.findMin(v);
}

Input

[15,35,85,96,5,6,8,12]

Output

5

Updated on: 04-May-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements