我试图实现一个递归合并排序算法来对一个简单的整数数组进行排序,但是我在数组的后半部分得到了奇怪的索引值。考虑到它的递归实现,上半部分似乎很好,令人困惑。随机整数数组在我的main方法中初始化。
public class MergeSort {
public static int Rounds = 1;
public static void MergeSort(Comparable[] ToSort, Comparable[] temp, int first, int last) {
if(first < last) {
int mid = (first + last) / 2;
//Test Block
System.out.print("For Round " + Rounds + ":\n");
System.out.print("first = " + first + " mid = " + mid + " last = " + last + "\n");
Rounds++;
System.out.print("Array in Round " + (Rounds - 1) + " = {");
for(int i = 0; i <= ToSort.length - 1; i++) {
System.out.print(ToSort[i]);
if(i < ToSort.length - 1)
System.out.print(", ");
else {
System.out.print("}\n\n");
}
}
MergeSort(ToSort, temp, first, mid);
MergeSort(ToSort, temp, mid + 1, last);
Merge(ToSort, temp, first, mid + 1, last);
}
}
public static void Merge(Comparable[] ToSort, Comparable[] temp, int first, int mid, int last) {
int beginHalf1 = first;
int endHalf1 = mid - 1;
int beginHalf2 = mid;
int endHalf2 = last;
int index = first;
int Elements = (last - first) + 1;
while(beginHalf1 <= endHalf1 && beginHalf2 <= endHalf2) {
if(ToSort[beginHalf1].compareTo(ToSort[beginHalf2]) < 0) temp[index++] = ToSort[beginHalf1++];
else temp[index++] = ToSort[beginHalf2++];
}
while(beginHalf1 <= endHalf1) temp[index++] = ToSort[beginHalf1++];
while(beginHalf2 <= endHalf2) temp[index++] = ToSort[beginHalf2++];
for(int i = 0; i < Elements; i++, last--) ToSort[last] = temp[last];
}
}
这会产生以下输出:
UNSORTED ARRAY = {15,9,12,19,49,43,57,70,78,87} 第1轮: first = 0 mid = 4 last = 9 第1轮中的数组= {15,9,12,19,49,43,57,70,78,87}
第二轮: first = 0 mid = 2 last = 4 第2轮数组= {15,9,12,19,49,43,57,70,78,87}
第3轮: first = 0 mid = 1 last = 2 第3轮数组= {15,9,12,19,49,43,57,70,78,87}
第4轮: first = 0 mid = 0 last = 1 第4轮数组= {15,9,12,19,49,43,57,70,78,87}
第五轮: first = 3 mid = 3 last = 4 第5轮数组= {9,12,15,19,49,43,57,70,78,87}
第6轮: first = 5 mid = 7 last = 9 第6轮数组= {9,12,15,19,49,43,57,70,78,87}
第7轮: first = 5 mid = 6 last = 7 第7轮数组= {9,12,15,19,49,43,57,70,78,87}
第8轮: first = 5 mid = 5 last = 6 第8轮数组= {9,12,15,19,49,43,57,70,78,87}
第9轮: first = 8 mid = 8 last = 9 第9轮数组= {9,12,15,19,49,43,57,70,78,87}
答案 0 :(得分:1)
您的实施没有错误。如果在应用MergeSort
方法后打印数组,则会对其进行排序:
Comparable[] a = new Comparable[]{15, 9, 12, 19, 49, 43, 57, 70, 78, 87};
Comparable[] b = new Comparable[a.length];
MergeSort.MergeSort(a, b, 0, a.length - 1);
for (int i = 0; i <= a.length - 1; i++) {
System.out.print(a[i]);
if (i < a.length - 1)
System.out.print(", ");
else {
System.out.print("}\n\n");
}
}
将打印9, 12, 15, 19, 43, 49, 57, 70, 78, 87}