Javatpoint Logo
Javatpoint Logo

C++ Algorithm partition()

C++ Algorithm partition() function is used to make partition the elements on the basis of given predicate (condition) mentioned in its arguments. If the container is partitioned then this function returns true, else returns false.

Syntax

Parameter

first: An bidirectional iterator pointing to the first element in the range to be partitioned.

last: An bidirectional iterator pointing to the past last element in the range to be partitioned.

pred: A user-defined unary predicate function that defines the condition to be satisfied if an element is to be classified.

Return value

This function returns an iterator to the first element of the range to not satisfy the predicate condition.

Complexity

Complexity is linear in the range [first, last): Applies pred to each element, and possibly swaps some of them.

Data races

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

Exceptions

This function throws an exception if either an element swap or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of partition():

Output:

odd elements: 1 9 3 7 5
even elements: 6 4 8 2

In the above example, elements from 1 to 9 are partitioned into even and odd elements.

Example 2

Let's see another simple example:

Output:

Vector v1 is ( 4 10 7 8 0 5 2 1 6 9 3 ).
The partitioned set of elements in v1 is: ( 9 10 7 8 6 5 2 1 0 4 3 ).

Example 3

Let's see another simple example to quick sort the elements of vector using partition() function:

Output:

Original vector:
    0 1 2 3 4 5 6 7 8 9 
Partitioned vector:
    0 8 2 6 4  * 5 3 7 1 9 
Unsorted list:
    1 30 -4 3 5 -4 1 6 -8 2 -5 64 1 92 
Sorted using quicksort:
    -8 -5 -4 -4 1 1 1 2 3 5 6 30 64 92

Example 4

Let's see another simple example:

Output:

Before Partition: 1 2 3 4 5 
After partition: 4 2 3 1 5 

Is it partitioned?
Yes, it is partitioned

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