Skip to content
This repository has been archived by the owner on Nov 8, 2023. It is now read-only.

Commit

Permalink
Merge pull request #198 from KiSobral/PartitionAlgorithm
Browse files Browse the repository at this point in the history
partition
  • Loading branch information
Bhupesh-V authored Nov 5, 2019
2 parents 0552650 + be4cc2b commit 4414571
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions algorithm/partition.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Partition

**Description :** This function is used to partition the elements on basis of condition mentioned in its arguments.

**Example**:
```cpp

// Possible implementation of partition
template<class ForwardIt, class UnaryPredicate>
ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPredicate p){

first = std::find_if_not(first, last, p);

// Condition to verify if first equals to last
if (first == last){
return first;
}

// Applying the condition
for (ForwardIt i = std::next(first); i != last; ++i){
if (p(*i)){
std::iter_swap(i, first);
++first;
}
}

return first;
}

int main(){
std::vector<int> my_vector = { 2, 1, 5, 6, 8, 7 };

// Partitioning my_vector in basis of even numbers condition
std::partition(my_vector.begin(), my_vector.end(), [](int x){
return x%2==0;
});

// Verifying if my_vector is partitioned
if ( std::is_partitioned(my_vector.begin(), my_vector.end(), [](int x){ return x%2==0; } ) ) {
std::cout << "The vector is partitioned!\n" << std::endl;
} else{
std::cout << "The vector is not partitioned!\n" << std::endl;
}

}

```
**[Run Code](https://rextester.com/FGSWB8639)**

0 comments on commit 4414571

Please sign in to comment.