The C++ function std :: is_sorted checks if the elements in range [first, last] are sorted in ascending order. Elements are compared using < operator.
There are two variants of std::is_sorted:
- Without using Binary predicate
bool is_sorted( ForwardIt first, ForwardIt last );
first, last : the range of elements to examine
Return value :
true: if the elements are in non-decreasing order.
false: any element in increasing order.
- Example :
Given a container of size n, and a range between [0 … n], write a program to check if it is sorted in ascending order or not. Equal values are allowed in array and two consecutive equal values are considered sorted.
Input : 2 5 9 4 /*Range = 3*/
Output : Sorted in given range.
Input : 3 5 1 9 /*Range = 3*/
Output : Not sorted in given range.
-
CPP
#include <iostream>
#include <algorithm>
int main()
{
int A[] = { 10, 11, 15, 12 };
int range1 = 3;
int range2 = 4;
if (std::is_sorted(A, A + range1)) {
std::cout << "Sorted in the range : " << range1 << std::endl;
} else {
std::cout << "Not Sorted in the range : " << range1 << std::endl;
}
if (std::is_sorted(A, A + range2)) {
std::cout << "Sorted in the range : " << range2 << std::endl;
} else {
std::cout << "Not Sorted in the range : " << range2 << std::endl;
}
return 0;
}
|
- Output :
Sorted in the range : 3
Not Sorted in the range : 4
- We have discussed other approaches here.
- Using binary predicate
bool is_sorted (ForwardIt first, ForwardIt last, Compare comp);
first, last : the range of elements to examine
comp : binary predicate
Return value :
true: if the elements are in non-decreasing order.
false: any element in increasing order.
- Example :
Given a string composed of characters only. Check if the characters are in sorted order. Also, Ignore the cases while comparing, i.e. ‘f’ > ‘A’
Input : AHZP
Output : Not Sorted
Input : Boy
Output : Sorted
-
CPP
#include <iostream>
#include <algorithm>
using namespace std;
bool ignore_case( char a, char b)
{
return ( tolower (a) <= tolower (b));
}
bool check_if_sorted(string str)
{
return is_sorted(str.begin(), str.end(), ignore_case);
}
int main()
{
string str = "tOY" ;
if (check_if_sorted(str)) {
cout << "Sorted" ;
}
else {
cout << "Not sorted" ;
}
return 0;
}
|
- Output :
Not sorted
- Time Complexity: The Complexity is linear in the distance between first and last: compares pairs of elements until a mismatch is found.
Last Updated :
31 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...