Javatpoint Logo
Javatpoint Logo

C++ Algorithm sort()

C++ Algorithm sort() function is used to sort the elements in the range [first, last) into ascending order.

The elements are compared using operator < for the first version, and comp for the second version.

Syntax

Parameter

first: An random access iterator pointing to the first element in the range to be sorted.

last: An random access iterator pointing to the past last element in the range to be sorted.

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

None

Complexity

The average of a sort complexity is N*log2 (N), where N = last - first.

Data races

The object in the range [first, last) are modified.

Exceptions

This function throws an exception if any of element comparisons, the element swaps 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 sort():

Output:

Before sorting: 3 1 4 2 5 
After sorting:  1 2 3 4 5

Example 2

Let's see another simple example:

Output:

myvector contains: 12 26 32 33 45 53 71 80

Example 3

Let's see another simple example:

Output:

Sorted list of functional programming languages - 
C#    C++    Java    Lisp    Pascal    Python    Sql    
Reverse Sorted list of functional programming languages - 
Sql    Python    Pascal    Lisp    Java    C++    C#  

Example 4

Let's see another simple example:

Output:

Original random shuffle vector vec1 data:
4 10 11 15 14 5 13 1 6 9 3 7 8 2 0 12 

Sorted vector vec1 data:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 

Re sorted (greater) vector vec1 data:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 

User defined re sorted vector vec1 data:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Next TopicC++ Algorithm





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA