C++ Algorithm is_sorted()
C++ Algorithm is_sorted() function returns true if the elements in the range [first, last) are sorted into ascending order.
The elements are compared using operator < for the first version, and comp for the second version.
Syntax
Parameter
first: An forward iterator pointing to the first element in the range to be checked.
last: An random access iterator pointing to the past last element in the range to be checked.
comp: A user defined binary predicate function that accepts two arguments and returns true if the two arguments are in order and false otherwise. It follows the strict weak ordering to order the elements.
Return value
It returns true if the range [first, last) is sorted into ascending order, false otherwise.
Complexity
The Complexity is linear in the distance between first and last: compares pairs of elements until a mismatch is found.
Data races
The object in the range [first, last) are accessed.
Exceptions
This function throws an exception if either an element comparison, or an operation on iterator throws an exception.
Note: The invalid parameters cause an undefined behavior. Example 1
Let’s see the simple example to demonstrate the use of is_sorted():
Output:
before sorting: is sorted? false after sorting : is sorted? True
Example 2
Let’s see another simple example:
Output:
a: 2 3 5 4 1 a: 2 3 5 1 4 a: 2 3 4 5 1 a: 2 3 4 1 5 a: 2 3 1 5 4 a: 2 3 1 4 5 a: 2 1 5 4 3 a: 2 1 5 3 4 a: 2 1 4 5 3 a: 2 1 4 3 5 a: 2 1 3 5 4 a: 2 1 3 4 5 a: 1 5 4 3 2 a: 1 5 4 2 3 a: 1 5 3 4 2 a: 1 5 3 2 4 a: 1 5 2 4 3 a: 1 5 2 3 4 a: 1 4 5 3 2 a: 1 4 5 2 3 a: 1 4 3 5 2 a: 1 4 3 2 5 a: 1 4 2 5 3 a: 1 4 2 3 5 a: 1 3 5 4 2 a: 1 3 5 2 4 a: 1 3 4 5 2 a: 1 3 4 2 5 a: 1 3 2 5 4 a: 1 3 2 4 5 a: 1 2 5 4 3 a: 1 2 5 3 4 a: 1 2 4 5 3 a: 1 2 4 3 5 a: 1 2 3 5 4 a: 1 2 3 4 5 the range is sorted!
The above example shows the sequence of sorting and prints the elements until it is sorted.
Example 3
Let’s see another simple example to check whether the elements are sorted or not:
Output:
3 1 4 1 5 : is_sorted: false 1 1 3 4 5 : is_sorted: true
Example 4
Let’s see another simple example:
Output:
Vector elements are not sorted in ascending order. Vector elements are sorted in ascending order.