Check if a vector is sorted in C++

In this article, we will discuss different ways to check if a vector is sorted or not in C++.

Iterate over all the elements of vector by index positions. For each element at ith index, check if it is either smaller or equal to the element at (i+1)th index position. If this condition evaluates to true for every element of vector, then it means that the given vector is sorted, otherwise it is not sorted. Let’s see an example,

Example 1:

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

// check if a vector is sorted or not
template <typename T>
bool sorted(vector<T> vec)
{
    bool result = true;
    for(int i = 0; i < vec.size()-1; i++)
    {
        if(vec[i] > vec[i+1])
        {
            result = false;
            break;
        }
    }
    return result;
}

int main()
{
    vector<int> vecObj {11, 22, 33, 44, 55, 66, 75, 88};

    // Check if a vector is sorted
    if ( is_sorted(vecObj.begin(), vecObj.end()) )
    {
        cout<< "Vector is sorted" << endl;
    }
    else
    {
        cout<< "Vector is not sorted" << endl;
    }

    return 0;

}

Output:

Vector is sorted

It confirmed that the vector is sorted.

Example 2:

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

// check if a vector is sorted or not
template <typename T>
bool sorted(vector<T> vec)
{
    bool result = true;
    for(int i = 0; i < vec.size()-1; i++)
    {
        if(vec[i] > vec[i+1])
        {
            result = false;
            break;
        }
    }
    return result;
}

int main()
{
    vector<int> vecObj {11, 20, 33, 40, 55, 12, 75, 88};

    // Check if a vector is sorted
    if ( is_sorted(vecObj.begin(), vecObj.end()) )
    {
        cout<< "Vector is sorted" << endl;
    }
    else
    {
        cout<< "Vector is not sorted" << endl;
    }

    return 0;

}

Output:

Vector is sorted

It confirmed that the vector is not sorted.

Summary

We learned a way to check if a vector is sorted or not in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top