Skip to content

Commit

Permalink
Partition
Browse files Browse the repository at this point in the history
  • Loading branch information
Cheukyin committed Jun 22, 2016
1 parent 525da7d commit 4df0766
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
33 changes: 33 additions & 0 deletions Algorithm/Sort/Partition.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#ifndef __CYTL__PARTITION__
#define __CYTL__PARTITION__

#include "Comparable.hpp"
#include <iterator>

namespace CYTL
{
template<class T>
void swap(T& t1, T& t2)
{
T tmp(t1);
t1 = t2;
t2 = tmp;
}

template<class Iterator, class Pred>
void partition(Iterator begin, Iterator end, Pred pred)
{
if(begin >= end) return;

Iterator lo = begin, hi = end-1;

while(lo < hi)
{
if( pred(*lo) ) lo++;
else swap(*lo, *(hi--));
}
}

}

#endif // __CYTL__PARTITION__
34 changes: 34 additions & 0 deletions Algorithm/Sort/PartitionTest.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include "Partition.hpp"
#include <assert.h>
#include <vector>
#include <iostream>

bool isOdd(int x)
{ return x % 2; }

bool lessThan5(int x)
{ return x < 5; }

int main()
{
std::vector<int> vec{1,2,3,4,5,6,7,8};

CYTL::partition(vec.begin(), vec.end(), isOdd);
assert(vec == (std::vector<int>{1,7,3,5,6,4,8,2}));

vec = {8,7,6,5,4,3,2,1};
CYTL::partition(vec.begin(), vec.end(), lessThan5);
assert(vec == (std::vector<int>{1,2,3,4,5,6,7,8}));

return 0;
}










0 comments on commit 4df0766

Please sign in to comment.