Javatpoint Logo
Javatpoint Logo

C++ Algorithm partial_sort()

C++ Algorithm partial_sort() function is used to rearrange the elements in the range[first, last), in such a way that the elements between the first and middle will be sorted and the elements between the middle and last will be in an unspecified order.

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

Syntax

Parameter

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

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

middle: A random access iterator pointing to the one past the final element in the sub-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

Average Complexity is less than linearithmic in the distance between first and last. Performs up to N*log (M) element comparisons where N = last - first and M = middle - first.

Data races

The objects in the range [first, last) are altered.

Exceptions

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

Output:

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

Example 2

Let's see another simple example:

Output:

myvector contains: 1 2 3 4 5 9 8 7 6

Example 3

Let's see a simple example for default version:

Output:

Before calling partial_sort

Numbers { 4 10 70 30 10 69 96 7  }

After calling partial_sort

Numbers { 4 7 10 10 70 69 96 30  }

Example 4

Let's see a simple example for custom (predicate) version:

Output:

Before calling partial_sort

Numbers { 4 10 70 30 10 69 96 7  }

After calling partial_sort

Numbers { 4 7 10 10 70 69 96 30  }

Next TopicC++ Algorithm




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA