Engineer bro!
Thu Nov 11 2021 (2 years ago)
Engineer by mistake!
I am a software engineer by passion
is_sorted
in C++ | STL | CPPis_sorted
function in STL is used to check if the input array is sorted or not. By default, it uses the binary operator to compare the elements, but you can customize the behaviour by passing the comparison function.
Note - you must include the header
bits/stdc++.h
is_sorted
function is used to check if the element in the range is sorted or not.
int ar[] = {1, 2, 3, 4};
if (is_sorted(ar1, ar1 + size)) {
cout << "array is sorted\n";
} else
cout << "array is not sorted\n";
// array is sorted
In order to check if the array is sorted in the reverse order, we have to pass the third argument (comparison function).
int ar[] = {5, 4, 3, 2};
if (is_sorted(ar1, ar1 + size,[](int a, int b) {
return a > b;
})) {
cout << "array is sorted\n";
} else
cout << "array is not sorted\n";
// array is sorted
Comparision function
// this is a lambda function
// pass it as a comparison function
[](int a, int b) {
// do whatever kind of comparison you want
return a > b;
}
The above comparison function will check if the previous element is greater than the next element or not.
© 2021 dsabyte. All rights reserved