【发布时间】:2013-11-16 05:19:11
【问题描述】:
我有一个规范,要求我创建一个带有文本字段和三个按钮的 GUI。文本字段将接受 5 个数字并将它们存储为数组,根据您单击的按钮,它们将通过冒泡排序、合并排序或快速排序进行排序,显示所采取的每一步。
我的 bubbleSort 输出将显示我的意思的示例:
5 3 2 6 2(开始)
3 5 2 6 2
[剪辑]
2 2 3 5 6
2 2 3 5 6(完)
在我制作 GUI 之前,它应该足够简单(规范的目的是教授排序,而不是 GUI 机制),我认为为每一个单独创建一个类并测试它们是个好主意在他们自己的电源中,以确保我理解逻辑。 bubbleSort 很简单,而且我似乎在 quickSort 上取得了进展,但我无法让 mergeSort 以我想要的方式工作。
我尝试了很多方法,包括制作一个外部计数器,在打印 5 个术语时强制下一行开始,但均无济于事。我能找到的关于该主题的唯一其他资源是:How to print out step by step process in MergeSort,但我无法掌握如何应用已接受的答案,这似乎是有道理的。
我当前的代码如下,我的错误打印被注释掉了。然而,排序逻辑本身似乎工作正常。
public class MergeSort {
public static void mergeSort(int[] list) {
if (list.length > 1) {
int[] firstHalf = new int[list.length / 2];
System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
mergeSort(firstHalf);
int secondHalfLength = list.length - list.length / 2;
int[] secondHalf = new int[secondHalfLength];
System.arraycopy(list, list.length / 2, secondHalf, 0,
secondHalfLength);
mergeSort(secondHalf);
merge(firstHalf, secondHalf, list);
// for (int j = 0; j < list.length; j++) {
// System.out.print(list[j] + " ");
// counter++;
// if (counter == size) {
// System.out.println();
// counter = 0;
// }
// }
// System.out.println();
}
}
public static void merge(int[] list1, int[] list2, int[] temp) {
int current1 = 0;
int current2 = 0;
int current3 = 0;
while (current1 < list1.length && current2 < list2.length) {
if (list1[current1] < list2[current2]) {
temp[current3++] = list1[current1++];
// for (int j = 0; j < current3; j++) {
// System.out.print(temp[j] + " ");
// }
// for (int j = 0; j < current1; j++) {
// System.out.print(list1[j] + " ");
// }
System.out.println();
} else {
temp[current3++] = list2[current2++];
}
}
while (current1 < list1.length) {
temp[current3++] = list1[current1++];
}
while (current2 < list2.length) {
temp[current3++] = list2[current2++];
}
}
public static void main(String args[]) {
int[] list = { 5, 3, 2, 6, 2 };
for (int j = 0; j < list.length; j++) {
System.out.print(list[j] + " ");
}
System.out.println();
mergeSort(list);
for (int j = 0; j < list.length; j++) {
System.out.print(list[j] + " ");
}
}
}
任何见解将不胜感激!
【问题讨论】:
标签: java eclipse sorting mergesort