我的代码目前工作正常,但我的麻烦是理解为什么它的工作原理。为什么某些参数需要它们以及为什么必须要发生。我尝试了另外两个解决方案,这似乎是唯一有效的解决方案。
public static int invCounter(int[] ranking)
{
int[] b = new int[ranking.length];
int[] aux = new int[ranking.length];
for (int i = 0; i < ranking.length; i++)
b[i] = ranking[i];
int inversions = mergeSortInv(ranking, b, aux, 0, ranking.length - 1);
return inversions;
}
private static int mergeInv(int[] a, int[] aux, int lo, int mid, int hi) {
int inversions = 0;
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (aux[j] < aux[i]) { a[k] = aux[j++]; inversions += (mid - i + 1); }
else a[k] = aux[i++];
}
return inversions;
}
private static int mergeSortInv(int[] a, int[] b, int[] aux, int lo, int hi) {
int inversions = 0;
if (hi <= lo) return 0;
int mid = lo + (hi - lo) / 2;
inversions += mergeSortInv(a, b, aux, lo, mid);
inversions += mergeSortInv(a, b, aux, mid+1, hi);
inversions += mergeInv(b, aux, lo, mid, hi);
return inversions;
}
如果有人能够解释为什么这种方法有效以及它如何运作会很棒。