我在12个文件中有12个预先订购的Integer []数组。我想像在mergeSort中一样将它们合并在一起,不同之处在于我可以在排序之前将它们组合成一个数组。我必须将它们分开,它们的大小不能超过50个。
要求如下: 使用合并技术对各个块进行相互排序,并将输出写入名为" result_using_merge.txt"的文件。
使用名为" potentialMinimums"的整数基元数组。保持当前的最小值并在每次迭代时打印出来。
你怎么建议我去做?
解决:
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;
}
}