I have 12 pre-ordered Integer[] arrays in 12 files. I'd like to merge them together just like I would in a mergeSort, with the difference that I can't combine them into one array before sorting. I must keep them separate and their size cannot exceed 50.
The requirement is as follows: Use the merging technique to sort the various chunks with respect to each other and write the output to a file called "result_using_merge.txt".
Use the array of integer primitives called "potentialMinimums" to hold the current minimums and print it at each iteration of the sorting.
How do you suggest I go about it?
SOLVED:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
public class BasicArrayMerger
{
private static ArrayList<Integer> finalCollection = new ArrayList<Integer>();
private static ArrayList<Integer> minCollection;
private static int[] minIndex =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private static int[] maxIndex =
{ 49, 49, 27, 49, 49, 27, 49, 49, 27, 49, 49, 27 };
private static Integer[] minimums;
private static ArrayList<Integer[]> inputs;
static PrintWriter outputStream, runStream;
static void mergeSortedArrays(final int memorySize,
ArrayList<Integer[]> inputChunks, Integer[] potentialMinimums,
String outfile)
{
try {
outputStream= new PrintWriter(outfile);
runStream = new PrintWriter("resources/RUN_merge.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
inputs = new ArrayList<Integer[]>(inputChunks);
int totalInts = 512;
int processedInts = 0;
while (processedInts < totalInts)
{
minCollection = new ArrayList<Integer>();
minimums = potentialMinimums;
while (minCollection.size() < memorySize && processedInts < totalInts)
{
for (int i = 0; i < inputs.size(); i++)
{
if (minIndex[i] > maxIndex[i])
minimums[i] = 9999;
else
minimums[i] = inputs.get(i)[minIndex[i]];
}
Integer value = findMin(minimums);
if (processedInts%10==0)
{
runStream.println("\n\n******"+processedInts+" iteration:");
runStream.println(Arrays.toString(minimums));
}
int valueIndex = findMinIndex(minimums);
if (value == 9999)
break;
else
minCollection.add(value);
minIndex[valueIndex] += 1;
processedInts++;
}
outputStream.println(minCollection);
finalCollection.addAll(minCollection);
}
outputStream.close();
runStream.close();
}
public static int findMin(Integer[] minimums)
{
if (minimums.length == 0)
return -1;
int small = minimums[0];
int index = 0;
for (int i = 0; i < minimums.length; i++)
if (minimums[i] < small) {
small = minimums[i];
index = i;
}
return small;
}
public static int findMinIndex(Integer[] minimums)
{
if (minimums.length == 0)
return -1;
int small = minimums[0];
int index = 0;
for (int i = 0; i < minimums.length; i++)
if (minimums[i] < small) {
small = minimums[i];
index = i;
}
return index;
}
}