Signup/Sign In
LAST UPDATED: NOVEMBER 1, 2020

C++ Find Minimum Element in a Rotated Sorted Vector Program

Hello Everyone!

In this tutorial, we will demonstrate the logic of Finding the Minimum Element in a Rotated Sorted Vector, in the C++ programming language.

What is a Rotated Sorted Vector?

A Rotated Sorted Vector is a sorted vector rotated at some pivot element unknown to you beforehand.

Example: [4,5,6,7,0,1,2] is one of the rotated sorted vector for the sorted vector [0,1,2,4,5,6,7].

For a better understanding of its implementation, refer to the well-commented CPP code given below.

Code:

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int findMin(vector<int> &m)
{
    int i;
    int n = m.size();
    for (i = 0; i < n; i++)
    {
        if (i == 0)
        {
            if (m[i] < m[n - 1] && m[i] < m[1])
                break;
        }
        else
        {
            if (m[i] < m[i - 1] && m[i] < m[(i + 1) % n])
                break;
        }
    }

    return m[i % n];
}

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " ===== Program to find the Minimum element in a rotated Sorted Vector, in CPP  ===== \n\n\n";

    cout << " ===== Logic: The minimum element will have larger number on both right and left of it.   ===== \n\n\n";

    //initializing vector with the following elements
    vector<int> v = {4, 5, 6, 7, 1, 3, 2};

    int n = v.size();

    int mini = 0;

    cout << "The elements of the given vector is : ";

    for (int i = 0; i < n; i++)
    {
        cout << v[i] << "  ";
    }

    mini = findMin(v);

    cout << "\n\nThe Minimum element in the given vector is: " << mini;

    cout << "\n\n\n";

    return 0;
}

Output:

C++ rotated sorted vector

We hope that this post helped you develop a better understanding of the concept of finding a minimum element in the rotated sorted vector and its implementation in CPP. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.