重复排序问题排序,
这是我的代码..
我成功排序了第一个数组,但是在第二个数组中(重复的字符串)它似乎没有按顺序输出,你能帮我跟踪我的代码中的错误吗?
import java.util.*;
public class NewClass {
public static void main(String[] args) {
String[] ClassOne = { "Kring", "Panda", "Soliel", "Darryl", "Chan", "Matang", "Jollibee.", "Inasal" };
String[] ClassTwo = { "Minnie", "Kitty", "Madonna", "Miley", "Zoom-zoom", "Cristine", "Bubbles", "Ara", "Rose", "Maria" };
String[] names = new String[ClassOne.length + ClassTwo.length];
mergeSort(ClassOne);
mergeSort(ClassTwo);
merge(names, ClassOne, ClassTwo);
mergeSort(names);
//Arrays.sort(names);
for (String ClassThree : names) {
System.out.println(ClassThree);
}
}
public static void mergeSort(String[] names) {
if (names.length > 2) {
String[] left = new String[names.length / 2];
String[] right = new String[names.length - names.length / 2];
for (int i = 0; i < left.length; i++) {
left[i] = names[i];
}
for (int i = 0; i < right.length; i++) {
right[i] = names[i + names.length / 2];
}
mergeSort(left);
mergeSort(right);
merge(names, left, right);
}
}
public static void merge(String[] names, String[] left, String[] right) {
int a = 0;
int b = 0;
for (int i = 0; i < names.length; i++) {
if (b >= right.length || (a < left.length && left[a].compareToIgnoreCase(right[b]) < 0)) {
names[i] = left[a];
a++;
} else {
names[i] = right[b];
b++;
}
}
}
}
并且继承了输出::
Ara
Chan
Cristine
Bubbles
Jollibee.
Inasal
Kring
Madonna
Matang
Miley
Minnie
Kitty
Panda
Rose
Maria
Soliel
Darryl
Zoom-zoom
...
答案 0 :(得分:5)
更改
if (names.length > 2) {
与
if (names.length >= 2) {
输出
Ara
Bubbles
Chan
Cristine
Darryl
Inasal
Jollibee.
Kitty
Kring
Madonna
Maria
Matang
Miley
Minnie
Panda
Rose
Soliel
Zoom-zoom
答案 1 :(得分:1)
只需改变一下:
if (names.length > 2)
到
if (names.length > 1)
mergeSort
以递归方式将数组分成两半,然后合并它们并返回调用链。当传递给mergeSort
的数组的长度是&lt; = 1时,它认为数组已排序,这称为基本情况。
答案 2 :(得分:0)
为什么不将两个数组(String ClassOne和ClassTwo)连接成一个,然后在一个数组上调用MergeSort?在我看来,你的过程使程序更加模糊。