The task is to merge 2 text files containing sorted integers into one file. Each number in both files is stored in new line(there are no empty lines,and only numbers are stored). Requirements are that if file1
has n numbers and file2
has m numbers, running time must be O(n+m) and memory consumption O(1).
My current solution is based on this algorithm:
while (not end of List A and not end of List B) if (List A current item <= List B current item) output List A current item advance List A index else output List B current item advance List B index // At this point, one of the lists is empty. // Output remaining items from the other while (not end of List A) output List A current item advance List A index while (not end of List B) output List B current item advance List B index
The solution is working fine, I've tested it for different cases.But, I'm looking for you opinion and suggestions, how can I improve the code, since it is quite huge.
Also, can I avoid assigning value to item 1
and item 2
variables at beginning? If I leave them unassigned, even if I pass them value
visual studio is returning error saying that I'm using unassigned variables in while loop
.
public static void Merge(string pathInputFile1, string pathInputFile2, string pathOutputFile)
{
int item1 = 0;
int item2 = 0;
bool endOfFile1 = false;
bool endOfFile2 = false;
string temp;
var inputFile1 = File.OpenText(pathInputFile1);
var inputFile2 = File.OpenText(pathInputFile2);
temp = inputFile1.ReadLine();
if (temp == null)
{
endOfFile1 = true;
}
else
{
item1 = Int32.Parse(temp);
}
temp = inputFile2.ReadLine();
if (temp == null)
{
endOfFile2 = true;
}
else
{
item2 = Int32.Parse(temp);
}
while (!endOfFile1 && !endOfFile2)
{
if (item1 < item2)
{
using (StreamWriter sw = File.AppendText(pathOutputFile))
{
sw.WriteLine(item1);
}
temp = inputFile1.ReadLine();
if (temp == null)
{
endOfFile1 = true;
}
else
{
item1 = Int32.Parse(temp);
}
}
else if (item1 == item2)
{
using (StreamWriter sw = File.AppendText(pathOutputFile))
{
sw.WriteLine(item1);
}
temp = inputFile1.ReadLine();
if (temp == null)
{
endOfFile1 = true;
}
else
{
item1 = Int32.Parse(temp);
}
temp = inputFile2.ReadLine();
if (temp == null)
{
endOfFile2 = true;
}
else
{
item2 = Int32.Parse(temp);
}
}
else
{
using (StreamWriter sw = File.AppendText(pathOutputFile))
{
sw.WriteLine(item2);
}
temp = inputFile2.ReadLine();
if (temp == null)
{
endOfFile2 = true;
}
else
{
item2 = Int32.Parse(temp);
}
}
}
while (!endOfFile1)
{
using (StreamWriter sw = File.AppendText(pathOutputFile))
{
sw.WriteLine(item1);
}
temp = inputFile1.ReadLine();
if (temp == null)
{
endOfFile1 = true;
}
else
{
item1 = Int32.Parse(temp);
}
}
while (!endOfFile2)
{
using (StreamWriter sw = File.AppendText(pathOutputFile))
{
sw.WriteLine(item2);
}
temp = inputFile2.ReadLine();
if (temp == null)
{
endOfFile2 = true;
}
else
{
item2 = Int32.Parse(temp);
}
}
}
}