

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Questions & Answers
- Find Minimum in Rotated Sorted Array II in C++
- Find the Rotation Count in Rotated Sorted array in C++
- Search in Rotated Sorted Array in Python
- Search in Rotated Sorted Array II in C++
- Search in Rotated Sorted Array II in Python
- Maximum element in a sorted and rotated array in C++
- Check if an array is sorted and rotated in C++
- Check if an array is sorted and rotated in Python
- Finding smallest element in a sorted array which is rotated in JavaScript
- How to find the number of times array is rotated in the sorted array by recursion using C#?
- Program to check whether an array Is sorted and rotated in Python
- Count rotations in sorted and rotated linked list in C++
- Program to find maximum weighted sum for rotated array in Python
- Count elements less than or equal to a given value in a sorted rotated array in C++
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted in Python
Advertisements