Last Updated : 19 Nov, 2024
In C++, is_sorted() is a built-in function used to check whether the element of the given range is sorted or not in ascending order. In this article, we will learn about is_sorted() function in C++.
Let’s take a quick look at a simple example that illustrates is_sorted() method:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 5, 6, 8, 9};
// Checking if vector v is sorted or not
if (is_sorted(v.begin(), v.end()))
cout << "Sorted";
else
cout << "Not Sorted";
return 0;
}
Given Vector is Sorted
Explanation: By default, is_sorted() function checks whether the range is sorted or not in ascending order. As the vector v is sorted in ascending, the function returned true. Let's look at is_sorted() in detail.
This article covers the syntax, usage, and common examples of is_sorted() method in C++:
Syntax of is_sorted()The is_sorted() is defined inside <algorithm> header file.
Parametersis_sorted(first, last);
is_sorted(first, last, comp);
The following examples demonstrates the use of is_sorted() method in different scenario:
Check if an Array is Sorted in Ascending Order C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {4, 7, 8, 9};
int n = sizeof(arr)/sizeof(arr[0]);
// Check whether array is sorted in ascending
// order
if (is_sorted(arr, arr + n))
cout << "Sorted";
else
cout << "Not Sorted";
return 0;
}
Given Array is SortedCheck if a List is Sorted in Descending Order C++
#include <bits/stdc++.h>
using namespace std;
// Comparator function
bool comp(int a, int b) {
return a > b;
}
int main() {
list<int> l = {9, 7, 6, 3};
// Check vector Sorted in descending order
if (is_sorted(l.begin(), l.end(), comp))
cout << "Sorted";
else
cout << "Not Sorted";
return 0;
}
Given Vector is Sorted
Explanation: As by default, is_sorted() checks for ascending order, we have to provide custom comparison function to check for descending order.
Check if Vector of String is in Lexicographically Ordered C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> v = {"hi", "geeks", "welcome", "to" "geeksforgeeks"};
// Check vector sorted in user
// defined order or not
if (is_sorted(v.begin(), v.end()))
cout << "Sorted";
else
cout << "Not Sorted";
return 0;
}
Given Vector is SortedCheck if Set is Sorted in Descending Order C++
#include <bits/stdc++.h>
using namespace std;
// Comparator function
bool comp(int a, int b) {
return a > b;
}
int main() {
set<int> s = {9, 7, 6, 3};
// Check vector Sorted in descending order
if (is_sorted(s.begin(), s.end(), comp))
cout << "Sorted";
else
cout << "Not Sorted";
return 0;
}
Explanation: The set is already sorted in ascending order. We have used is_sorted() with custom comparator to check if the set is in descending order.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4