【发布时间】:2015-07-09 02:50:24
【问题描述】:
我有这个现有的代码,我需要为其添加一个交换和比较计数器。到目前为止,我相信我的计数是正确的,但是我无法让输出不显示每个交换的循环。
public void 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
mergeSort(left,howMany);
mergeSort(right, howMany);
// merge the sorted halves into a sorted whole
merge(a, left, right);
}
}
// Merges the left/right elements into a sorted result.
// Precondition: left/right are sorted
public static void merge(int[] result, int[] left,
int[] right) {
int i1 = 0; // index into left array
int i2 = 0; // index into right array
int compCount = 0;
int swapCount = 0;
for (int i = 0; i < result.length; i++) {
compCount++;
if (i2 >= right.length ||
(i1 < left.length && left[i1] <= right[i2])) {
result[i] = left[i1]; // take from left
i1++;
swapCount++;
} else {
result[i] = right[i2]; // take from right
i2++;
swapCount++;
}
}
//figure this loop issue out System.out.println("merge sort " + compCount + " " + swapCount);
}
【问题讨论】:
-
您是否尝试在所有递归调用完成后获取交换总数并进行比较?
-
是的,我正在尝试系统输出结果以了解每种排序方法的工作原理。
标签: java sorting merge compare swap