Find Minimum in Rotated Sorted Array in C++

C++Server Side ProgrammingProgramming

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

Example

Let us see the following implementation to get better understanding −

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

Input

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

Output

5
raja
Published on 03-Feb-2020 11:02:18
Advertisements