Engineer bro!

Thu Nov 11 2021 (2 weeks ago)

Engineer by mistake!

I am a software engineer by passion

The use of is_sorted in C++ | STL | CPP

is_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.

Table of contents

Note - you must include the header bits/stdc++.h

is_sorted

is_sorted function is used to check if the element in the range [first,last)[first,last) is sorted or not.

Demo

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

Check if the array is sorted in the reverse order or not

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.

Reference

cppstlis_sortedlib

Comments (0)

Discussions (0)


© 2021 dsabyte. All rights reserved