我有這個現有的代碼,我需要添加交換和比較計數器。到目前爲止,我相信我有正確的計數,但我無法得到輸出不顯示每個交換循環。合併排序計數數量的交換和比較
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);
}
你試圖讓掉期的總計數和所有的遞歸調用完成後進行比較? –
是的,我正在試圖結果,以瞭解每種排序方法的工作原理。 – sippycup