【发布时间】:2013-05-07 18:33:28
【问题描述】:
我正在努力在合并排序时获取比较和移动器的计数。由于Sort Comparisons Counter,我想我有我需要的递归,但我无法打印出来。我显然对编程很陌生,所以如果您能解释我缺少什么,我将不胜感激。
import java.util.Arrays;
public class MergeSort {
int count = 0;
/**
* @param args
*/
// Rearranges the elements of a into sorted order using
// the merge sort algorithm (recursive).
public int mergeSort(int[] a, int howMany) {
if (a.length >= 2) {
// split array into two halves
int[] left = Arrays.copyOfRange(a, 0, a.length/2);
int[] right = Arrays.copyOfRange(a, a.length/2, a.length);
// sort the two halves
howMany = mergeSort(left,howMany);
howMany = mergeSort(right, howMany);
// merge the sorted halves into a sorted whole
howMany = merge ( left, right, a, howMany);
}
return howMany;
}
// Merges the left/right elements into a sorted result.
// Precondition: left/right are sorted
public static int merge(int[] result, int[] left,
int[] right, int howMany) {
int i1 = 0; // index into left array
int i2 = 0; // index into right array
for (int i = 0; i < result.length; i++) {
if (i2 >= right.length ||
(i1 < left.length && left[i1] <= right[i2])) {
result[i] = left[i1]; // take from left
i1++;
} else {
result[i] = right[i2]; // take from right
i2++;
}
}
return howMany;
}
System.out.println(howMany); // ???
}
【问题讨论】:
-
public static void main(String []args){ System.out.println(callYouMethodHere(foo,bar)); }
-
在整个过程中再添加一些
System.out.println语句,以查看您的代码是否按您认为的那样工作。 -
方法的调用顺序是什么?通常 main 方法将首先被调用,但我认为你正在做相反的事情。并且 System.out.println 在 return 语句之后,它不会以任何方式执行