The writefile()
method should write out to the given output file all the integers in the given array, one per line. For this part, the merge method should return a new array big enough to hold the content of the first two arrays (a and b), and then the first two copied into that array, without regard for order.
This is what is put in the command line when running the program:
java Merge1 sorted1.txt sorted2.txt sortedout.txt
This is what is in sorted1.txt.
12 51 80 138 212 237 306 316 317 337 356 413 422 511 534 577 621 708 717 738 738 846 850 900
This is what is sorted2.txt:
33 41 77 101 157 164 192 235 412 415 484 499 500 533 565 630 667 786 846 851 911 949 968 986
How would I do this?
Here is my code so far:
import java.io.*;
import java.util.Scanner;
public class Merge1
{
public static void main(String[] args)
{
File sorted1 = new File (args[0]);
File sorted2 = new File (args[1]);
File sortedout = new File (args[2]);
try{
Scanner input = new Scanner(sorted1);
readfile(input);
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
try{
Scanner input = new Scanner(sorted2);
readfile(input);
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
try{
Scanner input = new Scanner(sortedout);
readfile(input);
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
} // end main
static int[] readfile(Scanner input)
{
String num = "";
while(input.hasNextInt())
{
num += input.nextInt() + " ";
}
String[] array = num.split(" ");
int[] list = new int[array.length];
for(int i = 0; i < array.length; i++)
{
list[i] = Integer.parseInt(array[i]);
System.out.println(list[i]);
}
return list;
} // end readfile
static void writefile(PrintStream output, int[] a)
{
output.println(merge(int[] a, int[]b));
} // end writefile
static int[] merge(int[] a, int[] b)
{
int[] answer = new int[a.length + b.length];
int i = 0;
int j = 0;
int k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
{
answer[k] = a[i];
k++;
i++;
}
else
{
answer[k] = b[j];
k++;
j++;
}
}
while (i < a.length)
{
answer[k] = a[i];
k++;
i++;
}
while (j < b.length)
{
answer[k] = b[j];
k++;
j++;
}
return answer;
} // end merge
} // end Merge1