I am implementing merge_sort
. As the merging cannot be done in place (according to my current knoweledge), i have to declare a temporary array
to store the values while merging.
Since it is a generic algorithm, the data type can be anything.
What can be a possible solution..?
Ans. One way to do it is to take another template argument T and get the data type, but i really dont want to change my function structure as it is like the ones i found on STL.
Here is my code :
template <class RandomAccessIterator>
void merge (RandomAccessIterator first,int N1,RandomAccessIterator second,int N2)
{
int i,j,k;
// How to declare the sorted_list array when data type is not known....
i = 0; // Inedex Of The First List
j = 0; // Index Of The Second List
k = 0; // Index Of The Sorted List
while (i<N1 && j<N2)
{
if (first[i] < second[j])
sorted_list[k++] = first[i++];
else
sorted_list[k++] = second[j++];
}
if (i == N1)
{
while (j < N2)
sorted_list[k++] = second[j++];
}
else
{
while (i < N1)
sorted_list[k++] = first[i++];
}
}
template <class RandomAccessIterator>
void merge_sort (RandomAccessIterator begin,RandomAccessIterator end)
{
int N = end - begin + 1;
int N1,N2;
if (N == 1)
return;
RandomAccessIterator mid = (begin + end)/2;
merge_sort (begin,mid);
merge_sort (mid+1,end);
N1 = end - begin + 1;
N2 = end - mid;
merge (begin,N1,mid+1,N2);
}