Skip to content

Instantly share code, notes, and snippets.

@phlandscape
Last active December 11, 2015 19:48
Show Gist options
  • Save phlandscape/4650813 to your computer and use it in GitHub Desktop.
Save phlandscape/4650813 to your computer and use it in GitHub Desktop.
relearning Merge Sort by implementing a templated version for STL containers with iterators
/* Author: phlandscape
* relearning Merge Sort by implementing
* templated version for STL containers with iterators
*
*/
#include <iostream>
#include <list>
// template functions
template<typename container, typename ITERATOR_TYPE>
void merge_sort_it_do(ITERATOR_TYPE first, ITERATOR_TYPE mid, ITERATOR_TYPE sec)
{
auto ii(first), ee(mid);
container temp;
while(ii != mid && ee != sec)
{
temp.push_back((*ii > *ee)? *ee++ : *ii++);
}
while(ii != mid)
{
temp.push_back(*ii++);
}
while(ee != sec)
{
temp.push_back(*ee++);
}
auto temp_it = temp.begin();
while(first != sec)
{
*first++ = *temp_it++;
}
}
/** Recursive merge sort with Iterators */
template<typename container, typename ITERATOR_TYPE>
void merge_sort_iterator(ITERATOR_TYPE first,ITERATOR_TYPE sec)
{
if(distance(first,sec) > 1)
{
ITERATOR_TYPE mid = first;
advance(mid, distance(first,sec)/2);
merge_sort_iterator<container,ITERATOR_TYPE>(first,mid);
merge_sort_iterator<container,ITERATOR_TYPE>(mid,sec);
merge_sort_it_do<container,ITERATOR_TYPE>(first,mid,sec);
}
}
template<typename container>
void merge_recursively(container& some)
{
merge_sort_iterator<container>(some.begin(),some.end());
}
template<typename container>
void merge_iteratively(container& some)
{
for(unsigned int i = 1; i < some.size(); i*=2)
{
for(unsigned int k = 0; k < some.size(); k+=2*i)
{
auto first(some.begin());
advance(first, k);
auto sec(first);
advance(sec, (2*i < (some.size()-k))? (2*i) : (some.size()-k));
auto mid = first;
advance(mid,distance(first,sec)/2);
merge_sort_it_do<container>(first,mid,sec);
}
}
}
template<typename container>
void PrintCon(const container& ctr)
{
std::cout << " | ";
for(auto it = ctr.begin(); it != ctr.end(); ++it)
{
std::cout << *it << " | ";
}
std::cout << std::endl;
}
// end of template functions
int main()
{
std::list<int> tester;
tester.push_back(423);
tester.push_back(611);
tester.push_back(224);
tester.push_back(343);
tester.push_back(324);
tester.push_back(423);
tester.push_back(798);
tester.push_back(597);
tester.push_back(673);
tester.push_back(237);
merge_iteratively(tester);
PrintCon(tester);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment