【发布时间】:2015-07-02 11:34:01
【问题描述】:
我正在尝试将两个数组排序为一个数组。 但我有一些问题。它没有正确排序。我附上了文件、代码和输出。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class MArray {
public static void mergeA(long[] A, long[] B) {
long [] merged = new long[A.length + B.length ];
int indexFirst = 0, indexSecond = 0, indexMerge = 0;
while (indexFirst < A.length && indexSecond < B.length) {
if (A[indexFirst] <= B[indexSecond]) {
merged[indexMerge++] = A[indexFirst++];
}
else {
merged[indexMerge++] = B[indexSecond++];
}
}
System.out.print("\n");
System.out.println("Here is your merged array: " );
for (int i = 0; i < merged.length; i++) {
System.out.print(merged[i] + ", ");
}
}
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
long array1[] = null;
long array2[] = null;
Scanner Scanscan = new Scanner(System.in);
System.out.print("Input filename: ");
String filename = Scanscan.nextLine();
File inputFile = new File(filename);
Scanner reader = new Scanner(inputFile);
int i = 0;
long array[] = new long[20];
while(reader.hasNext())
{
array[i] = reader.nextInt();
i++;
}
array1 = new long[i];
System.arraycopy(array, 0, array1, 0, i);
Arrays.sort(array1);
for (int i1 = 0; i1 < array1.length; i1++) {
System.out.print(array1[i1] + " ");
}
System.out.println( "\n");
System.out.println("Please enter your second file name: ");
String filename2 = Scanscan.nextLine();
File inputFile2 = new File(filename2);
Scanner reader2 = new Scanner(inputFile2);
int i1 = 0;
long temp1[] = new long[20];
while(reader2.hasNext())
{
temp1[i1] = reader2.nextInt();
i1++;
}
array2 = new long[i1];
System.arraycopy(temp1, 0, array2, 0, i1);
Arrays.sort(array2);
for (int i11 = 0; i11 < array2.length; i11++) {
System.out.print(array2[i11] + " ");
}
mergeA(array1, array2);
}
}
输入 1 2 4 6 8 10
输入 2 12 14 16 18 20 22 24
输出 输入文件名:input1_1.txt 2 4 6 8 10
Please enter your second file name:
input1_2.txt
12 14 16 18 20 22 24
Here is your merged array:
2, 4, 6, 8, 10, 0, 0, 0, 0, 0, 0, 0,
【问题讨论】:
-
当您将数组声明为
int[20]时,您会得到一个包含 20 个零的数组。 -
合并排序的
merge(int[], int[])方法不合并两个排序数组吗?我认为您需要阅读合并排序。并找到一个调试器 -
但是我的教授说要将所有数组的大小设置为 20....有没有办法解决这个问题?
-
合并排序不会合并 2 个数组。它拆分了一个原始数组,然后通过以正确的顺序将其合并在一起来对其进行排序(我知道的不好的解释)。基本上,在使用从一个数组开始的合并排序时,您不会从 2 个数组开始。
-
我的教授说将两个数组合并为一个按升序排列的数组。然后让第三个按顺序按住它们。