*嘿。所以我的mergeSorting出了问题。我尝试了不同的方法和方法,但无法使其发挥作用。我理解mergeSorting的原理,所以没有问题。 这是我的方法:
public static void TopDownMergeSort(int[] left, int[] right, int n){
TopDownSplitMerge(left, 0, n, right);
}
public static void CopyArray(int[] right, int start, int end, int[] left){
for (int i = start;i < end; i++){
right[i] = left[i];
}
}
public static void TopDownSplitMerge(int[] left, int start, int end, int[] right){
if (end - start < 2){
int middle = (end + start)/2;
TopDownSplitMerge(left, start, middle, right);
TopDownSplitMerge(left, middle, end, right);
TopDownMerge(left, start, middle, end, right);
CopyArray(right, start, end, left);
}
}
public static void TopDownMerge(int[]left, int start, int middle, int end, int[]right){
int i1 = start, i2 = middle;
for (int i = start; i < end; i++){
if (i1 < middle && (i2 >= end || left[i1] <= left[i2])){
right[i] = left[i1++];
}
else {
right[i] = left[i2++];
}
}
}
public static int[] mergeSort(int[] in) {
int[] arr = in.clone();
int[] temp = in.clone();
TopDownSplitMerge(arr,0,arr.length,temp);
return arr;
}
这就是我测试mergeSort的方法。
int[] list = {2,5,8,6,9,7,3,4};
System.out.println("Before mergesort: "+Arrays.toString(list));
int[] ne = SortingAlgorithms.mergeSort(list);
System.out.println("After mergesort: "+Arrays.toString(ne));
答案 0 :(得分:1)
if (end - start < 2)
错了。它应该是
if (end - start > 2)
答案 1 :(得分:0)
一些提示:
CopyArray
可以替换为System.arraycopy
...同时重新考虑:if (end - start < 2)
我建议您查看Thomas H. Cornmen的“算法简介”
,而不是修复代码