# Thread: Mergesort w/ numbers from txt file

1. ## Mergesort w/ numbers from txt file

Hi! I am supposed to write a code which uses a Merge Sort algorithm that reads from a file and prints it out to an output file. This is what I implemented so far and it doesn't seem to work correctly. I can do it with separate arrays but I need to use one data array with a temp array and it needs to be recursive. Can anyone point me in the right direction or see something wrong that I missed?

Input file:
911.876
468.77
405.136
954.823
25.9998

OutPut I get:
25.9998
468.77 <
405.136 <
911.876
954.823

What output should be:
25.9998
405.136
468.77
911.876
954.823

Code:
```#include <iostream>
#include <fstream>

using namespace std;

int mid = 0;
int n = 0;
int begin = 0;
ifstream infile("input.txt");
ofstream mergeout("lmergeout.txt");

void merge(double data[], int first, int last,int num)
{

double temp[num];
for(int i=0;i<num;i++)temp[i] = data[i];
int middle = (first+last)/2;
int i1=first;
int i2=first;
int i3=middle+1;
cout<<first<<endl;
cout<<middle<<endl<<last<<endl<<endl;
for(int i = 0;i<num;i++)
{
cout<<data[i]<<endl;
}
cout<<endl;

while(i2 <= middle && i3 <= last)
{
if(data[i2] < data[i3])
{
temp[i1++] = data[i2++];
//      temp[i2++] = data[i1++];

}
else
{
temp[i1++] = data[i3++];
//   temp[i3++] = data[i1++];

}
}

while(i3<=last) temp[i1++] = data[i3++];

while(i2<=middle) temp[i1++] = data[i2++];

for(int i = 0;i<num;i++)
{
data[i] = temp[i];
cout<<data[i]<<endl;
}

}

void mergesort(double data[], int first, int last,int num)
{
if (first < last)
{
mid = (first+last) / 2;
mergesort(data,first,mid,num);
mergesort(data,1 + mid,last,num);

merge(data,first,last,num);
cout<<endl;
}
}

int main()
{
n = 5;                              // Size of Array
double array_merge[n];  //The Array of Size 'n'
// Reads data and puts it in array
for(int j = 0;j<n;j++)
{
infile>>array_merge[j];
}
mergesort(array_merge, begin,n-1,n);
for(int j=0;j<n;j++)mergeout<<array_merge[j]<<endl;  //Prints file out```

2. What debugger are you using? Have you tried stepping through it?
That indentation is a bit of a mess, could you tidy it up a bit?

Popular pages Recent additions