我想对一组输入(来自命令行参数)进行排序,一直在这里停留3天而没有发现我的代码错误...真的很绝望......
有人请给我一个提示吗?
import java.util.Arrays;
public class MergeSorter
{
public MergeSorter(int[] anArray)
{
a = anArray;
}
public void sort()
{
if (a.length <= 1) return;
int[] first = new int[a.length / 2];
int[] second = new int[a.length - first.length];
System.arraycopy(a, 0, first, 0, first.length);
System.arraycopy(a, first.length, second, 0, second.length);
MergeSorter firstSorter = new MergeSorter(first);
MergeSorter secondSorter = new MergeSorter(second);
firstSorter.sort();
secondSorter.sort();
merge(first, second);
}
private void merge(int[] first, int[] second)
{
int iFirst = 0;
int iSecond = 0;
int j = 0;
while (iFirst < first.length && iSecond < second.length)
{
if (first[iFirst] < second[iSecond])
{
a[j] = first[iFirst];
iFirst++;
}
else
{
a[j] = second[iSecond];
iSecond++;
}
j++;
}
System.arraycopy(first, iFirst, a, j, first.length - iFirst);
System.arraycopy(second, iSecond, a, j, second.length - iSecond);
}
private int[] a;
public static void main(String[] args)
{
int[] a = new int[args.length];
for (int i = 0; i < args.length; i++)
{
a[i] = Integer.parseInt(args[i]);
}
MergeSorter sorter = new MergeSorter(a);
sorter.sort();
System.out.println(Arrays.toString(a));
}
}
答案 0 :(得分:1)
如果这不是Mergesort的练习,您可以简单地使用Arrays.sort(array);
,这是一个mergesort。
要按降序排序,您可以指定自己的比较器。
Arrays.sort(array, new Comparator<Integer>()
{
public int compare(Integer i1, Integer i2)
{
return -i1.compareTo(i2);
}
});
答案 1 :(得分:1)
运行测试代码:
Random r = new Random();
int testCase = 0;
out: while (true) {
System.out.println("Test case " + testCase++);
//Create array of random length (from 0 to 999) and random content
int[] a = new int[r.nextInt(1000)];
for (int i = 0; i < a.length; i++)
a[i] = r.nextInt();
//Try to sort (in ascending order)
MergeSorter sorter = new MergeSorter(a);
sorter.sort();
//Test if sorted
for (int i = 0; i < a.length-1; i++) {
if (a[i+1] < a[i]) //not ascending
{
System.out.println("Array is not sorted!");
System.out.println(Arrays.toString(a));
break out;
}
}
}
找不到任何分拣机没有排序的情况(我把它运行到大约1.000.000个测试用例)!
答案 2 :(得分:1)
它正常工作。 试着写:
java MergeSorter 7 3 5 3 5
它给出了:
[3,3,5,5,7]
但如果你写:
java MergeSorter 73535
它与输入相同,因为有一个int参数:
[73535]