我正在努力在合并排序时获取比较和移动器的计数。我想我需要递归,感谢这个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); // ???
}
答案 0 :(得分:0)
你需要通过它的对象调用方法,无论你想打印什么。这样的事情(可能在你的主要方法中):
MergeSort mObj - new MergeSort();
int[] array = {1,2,3};
int count = mObj.mergeSort(array, 2);
System.out.println(count);
答案 1 :(得分:0)
基本上,您需要一个驱动程序方法。运行java类时,它将查找public static void main(String[] args)
方法;如果此方法不存在,则不会发生任何事情。根据您现在拥有的内容,您实际上应该从System.out.println(howMany);
获得编译错误,因为变量howMany
仅存在于merge方法的范围(括号)中。为了更好地理解这一点,我将查看有关变量和方法范围以及类成员的注释。要快速修复,请删除我在上面提到的底部的行,并将此方法放在您的类中的某个位置:
public static void main(String[] args) {
int[] array = {2,5,8,1,3};
int howMany = mergeSort(array, 5);
System.out.println(howMany);
}
您还需要制作mergeSort
方法static
,因此请将其定义更改为
public **static** int mergeSort(int[] a, int howMany)
我测试了你的代码,我很确定它没有给出你想要的答案,所以一定要检查一下。祝你好运学习面向对象的编程!