This post will discuss how to check for a sorted array in C++.

1. Using std::is_sorted

The standard solution to check if an array is sorted is using the standard library algorithm std::is_sorted that takes a range and comparison function. With C++11, you can pass an iterator to the beginning and end of the array. It can be used as follows to check for a sorted array in ascending order using the default comparison operator.

Download  Run Code

 
Alternatively, you can specify the range to check using pointer notation:

Download  Run Code

 
To check for a sorted array in descending order, you can pass the comparison function std::greater<int>() that represents an object class for greater-than inequality comparison.

Download  Run Code

 
The default comparison function works fine for an array of std::string. However, if you have an array of C-style strings, you have to provide a comparison function.

Download  Run Code

2. Using std::adjacent_find function

Another option is to use the std::adjacent_find function to check for a sorted array in C++. It returns the first occurrence of adjacent elements that satisfies a binary predicate, or end of the range if no such pair is found.

To check for a sorted array in ascending order, you can pass the comparison function std::greater<int>(). If no pair is found that satisfies the comparison function, the array must be sorted.

Download  Run Code

 
Similarly, to check for a sorted array in descending order, pass the comparison function std::less<int>() that represents an object class for less-than inequality comparison.

Download  Run Code

3. Naive Solution

Finally, you can write your custom logic for this trivial task. Here’s what the code would look like to check for a sorted array in ascending order:

Download  Run Code

That’s all about checking for a sorted array in C++.