I need to implement the algorithm of mergesort with following interface:
template <typename T, typename Comp>
void mergesort(T begin, T end, Comp comp);
where begin and end - iterators for elements of some container of type T, comp - is function of comparing elements, which are stored in container. And
template <typename T, typename Comp>
void merge(T beginLeft, T endLeft, T beginRight, T endRight,
T beginResult, Comp comp);
is function of merging of two sorted containers (beginLeft and endLeft - iterators of the first container, beginRight and endRight - of the second) and result should be iterator to the begining of new merged container beginResult.
It should be look like this.
I've wrote recursive function for merge sort, which calls the procedure of merging.
template <typename T, typename Comp>
void mergesort(T begin, T end, Comp comp)
{
if (begin == std::prev(end))
{
return;
}
T middle = begin + std::distance(begin, end) / 2;
mergesort<T, Comp>(begin, middle, comp);
mergesort<T, Comp>(middle, end, comp);
merge<T, Comp>(begin, middle, middle, end, begin, comp);
}
template <typename T, typename Comp>
void merge(T beginLeft, T endLeft, T beginRight, T endRight,
T beginResult, Comp comp)
{
while (beginLeft != endLeft && beginRight != endRight)
{
if (comp(*beginLeft, *beginRight))
{
*beginResult = *beginLeft;
++beginResult;
++beginLeft;
}
else
{
*beginResult = *beginRight;
++beginResult;
++beginRight;
}
}
while (beginLeft != endLeft)
{
*beginResult = *beginLeft;
++beginResult;
++beginLeft;
}
while (beginRight != endRight)
{
*beginResult = *beginRight;
++beginResult;
++beginRight;
}
}
Function merge works correctly, but I don't quite understand, how mergesort should work. What argument should I pass to
merge<T, Comp>(begin, middle, middle, end, /?...?/, comp);
If I pass just begin there, than the result of sorting is not correct. Or should I pass there some temporary container. But how can I create it, if I have only type of iterator and don't know the type of elements?
I will be grateful for your help. Thank you!
--ADDED---
Example of merging:
vector<int> vec1;
vector<int> vec2;
vector<int> vec3(6);
vec1.push_back(1);
vec1.push_back(3);
vec1.push_back(5);
vec2.push_back(2);
vec2.push_back(4);
vec2.push_back(6);
merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), vec3.begin(), std::less<int>());
for (int i = 0; i < vec3.size(); ++i)
{
std::cout << vec3[i] << std::endl;
}
Output is: 1 2 3 4 5 6