# C++ Algorithm partial_sort_copy()

C++ Algorithm partial_sort_copy() function is similar to partial_sort() function which 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 middle and last will be in an unspecified order. But partial_sort_copy() function puts the result in a new range[result_first, result_last).

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

## Parameter

first: An input iterator pointing to the first element in the source range to be partially sorted.

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

result_first: A random access iterator pointing to the first element in the sorted destination range.

result_last: A random access iterator pointing to the past last element in the sorted destination range.

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 an iterator addressing to the element that follows the last element written in the result sequence.

## Complexity

Average Complexity is less than linearithmic in the distance between first and last. Performs up to N*log (min (N, 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.

## Example 1

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

Output:

```myvector contains: 1 2 3 4 5
```

## Example 2

Let's see another simple example for the default version:

Output:

```Before calling partial_sort_copy

Numbers { 4 10 70 30 10 69 96 7  }

After calling partial_sort_copy

Numbers { 4 10 70 30 10 69 96 7  }

Result { 4 7 10 10  }
```

## Example 3

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

Output:

```Before calling partial_sort_copy

Numbers { 4 10 70 30 10 69 96 7  }

After calling partial_sort_copy

Numbers { 4 10 70 30 10 69 96 7  }

Result { 4 7 10 10  }
```

## Example 4

Let's see another example:

Output:

```v0 : 4 2 5 1 3
v1 : 10 11 12
v2 : 10 11 12 13 14 15 16
Writing v0 to v1 in ascending order gives: 1 2 3
Writing v0 to v2 in descending order gives: 5 4 3 2 1 15 16
```

Next TopicC++ Algorithm

### Feedback   