I have the following C++ code that I need to implement merge-sort with. Its partially working but runs an infinite loop without sorting for some reason I cant spot. It also outputs 0.00 for part of the values instead of initial values. (e.g. input values 9.12 1.59 outputs 1.59 0.00) But when I have more than 2 elements is when it is an infinite loop and does no sorting. The extra printf()’s are needed for my assignment to be correct so you can disregard them for the analysis. Thanks in advance for any help!!
double max(double x, double y)
{
return (x > y) ? x : y;
}
void sort_doubles(vector <double> &v, int print)
{
int i;
vector<double> tmp;
tmp.resize(v.size());
recursive_sort(v, tmp, 0, v.size(), print);
printf("%16c",' ');
for (i = 0; i < v.size(); i++) printf(" %.2lf",v.at(i));
printf("\n");
}
void recursive_sort(vector<double> &v, vector<double> &temp, int start, int size, int print)
{
int i,mid,left,right;
double j;
if (size == 1) return;
i = 0;
mid = start + (size/2);
left = start;
right = start + mid;
printf("B: %5d %5d ",start, size);
for (i = 0; i < v.size(); i++) printf(" %.2lf", v.at(i));
printf("\n");
recursive_sort(v, temp, left, mid, print);
recursive_sort(v, temp, left+mid, size-mid, print);
for(i = 0; i < size; i++)
{
/* Check to see if any elements remain in the left array; if so,
* we check if there are any elements left in the right array; if
* so, we compare them. Otherwise, we know that the merge must
* use take the element from the left array */
if(left < start + mid && (right == start+size || max(v[left], v[right]) == v[left]))
{
temp[i] = v[right];
right++;
}
else
{
temp[i] = v[left];
left++;
}
}
/* Copy the sorted subarray back to the input */
for(i = start; i < start+size; i++)
{
v[i] = temp[i];
}
printf("E: %5d %5d ",start,size,' ');
for (i = 0; i < v.size(); i++) printf(" %.2lf",v.at(i));
printf("\n");
}
Figured it out finally! below is the code just in case someone might need it.