C++ Standard Library C++ STL Library

C++ <algorithm> - is_sorted() Function



The C++ algorithm::is_sorted function is used to check whether the given range is sorted or not. It returns true if the range [first,last) is sorted in increasing order, else returns false.

The elements are compared using operator< (in first version) or comp (in second version).

Syntax

//default version
template <class ForwardIterator>
  void is_sorted (ForwardIterator first, ForwardIterator last);

//custom version
template <class ForwardIterator, class Compare>
  void is_sorted (ForwardIterator first, ForwardIterator last, 
                  Compare comp);

Parameters

first Specify initial position of the forward iterator of the sequence. The range used is [first,last).
last Specify final position of the forward iterator of the sequence. The range used is [first,last).
comp Specify a binary function that accepts two element as arguments, and returns a value convertible to bool. The returned value indicates whether the first argument is considered to go before the second using the strict weak ordering it defines.

Return Value

Returns true if the range [first,last) is sorted in increasing order, false otherwise. The function always returns true, if the range contains less than two elements.

Time Complexity

Up to Linear i.e, Θ(n).

Example:

In the example below, the algorithm::is_sorted function is used to check whether the given range of elements are sorted in increasing order or not.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main (){
  vector<int> vec1= {10, 40, 30, 20};
  vector<int> vec2= {10, 20, 30, 40};

  cout<<boolalpha;
  cout<<"Is vec1 sorted: "<<
      is_sorted(vec1.begin(), vec1.end())<<"\n";
  cout<<"Is vec2 sorted: "<<
      is_sorted(vec2.begin(), vec2.end())<<"\n"; 

  return 0;
}

The output of the above code will be:

Is vec1 sorted: false
Is vec2 sorted: true

Example:

The example below shows how to use comp with algorithm::is_sorted function.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool less_than (double i, double j) {
  return ((int)i<(int)j);
}

int main (){
  vector<double> Vec= {1.8, 1.5, 55.5, 55.3, 55.8};

  cout<<boolalpha;
  cout<<"Is Vec sorted: "<<
      is_sorted(Vec.begin(), Vec.end())<<"\n";
  cout<<"Is Vec sorted (based on int value): "<<
      is_sorted(Vec.begin(), Vec.end(), less_than)<<"\n";   

  return 0;
}

The output of the above code will be:

Is Vec sorted: false
Is Vec sorted (based on int value): true

❮ C++ <algorithm> Library