Merge Sort Algorithm

I am supposed to implement a merge sort algorithm using the predefined functions. I was given 5 functions with 2 being input/output functions. The body of the function was supposed to be created by me to sort an input array from an input file and output it to an output file.

I cannot figure out why my code only sorts the input file num.txt which has an array of numbers "49 58 32 67 45 43 100 83 116 108 102 97 119 114 99 110" into sorted 2 number groups "49 58 32 67 43 45 83 100 108 116 97 102 114 119 99 110". My assignment has taken me 10 hours and I cannot figure it out. Please see if you can find the error in the code.

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

const int ArraySize = 50;

void File2Array(int a[], int& size);
void Array2File(int a[], int size);
void sortSegSize2(int a[], int size);
void mergeSegments(int a[], int size, int segSize, int offset);
void mergeSort(int a[], int size);


int main()
{
int a[ArraySize];
int size;
File2Array(a, size);
if(size<=1)
Array2File(a, size);
else
{
mergeSort(a, size);
Array2File(a, size);
}

return 0;
}

void File2Array(int a[], int& size)
{
int count = 0, input;
string infilename;
cout << "Please input the input filename: ";
cin >> infilename;
ifstream infile;
infile.open(infilename.c_str());

while(infile >> input)
a[count++] = input;

size = count;

infile.close();
}

void Array2File(int a[], int size)
{
string outfilename;
cout << "Please input the output filename: ";
cin >> outfilename;
ofstream outfile;
outfile.open(outfilename.c_str());

for(int i = 0; i < size; i++)
outfile << a[i] << " ";

outfile.close();
}

void sortSegSize2(int a[], int size)
{
int temp = 0;
for (int h=0; h<=size; h=h+2)
{
if (a[h+1]<a[h])
{
temp=a[h+1];
a[h+1]=a[h];
a[h]=temp;
}
}
}

//i think my problem may be in this function because the first one works fine
void mergeSegments(int a[], int size, int segSize, int offset)
{
int newx=0; int newy=0; int k=0;
int newArray[2*segSize];


if (newx != segSize && newy != segSize)
{

do{
if (a[offset+newx] > a[offset+segSize+newy])
{
newArray[k] = a[offset+segSize+newy];
k++;
newy++;
}
else if (a[offset+newx] < a[offset+segSize+newy])
{
newArray[k] = a[offset+newx];
k++;
newx++;
}
}while (newx != segSize && newy != segSize);
}

if (newx != segSize)
{
do{
newArray[k] = a[offset+newx];
k++;
newx++;

}while (newx != segSize);
}

if (newy != segSize)
{
do{

newArray[k] = a[offset+segSize+newy];
k++;
newy++;


}while (newy != segSize);

}
a = newArray;
}

// Edit the following code to make the mergeSort function work correctly.
void mergeSort(int a[], int size)
{
int segSize, offset, i, j;

sortSegSize2(a, size);
for(i=2; i< size; i= i * 2)
{
segSize = i;
for(j= 0; j < (size/segSize); j++)
{
offset = j*segSize;
mergeSegments(a, size, segSize, offset);
}
}
}

Topic archived. No new replies allowed.