Skip to content

Commit 19a5fab

Browse files
committed
1 parent 1b5f56d commit 19a5fab

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

src/main/java/org/cicirello/permutations/distance/KendallTauDistance.java

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/*
2-
* Copyright 2014, 2015, 2017-2022 Vincent A. Cicirello, <https://www.cicirello.org/>.
2+
* JavaPermutationTools: A Java library for computation on permutations and sequences.
3+
* Copyright (C) 2014, 2015, 2017-2022 Vincent A. Cicirello, <https://www.cicirello.org/>.
34
*
45
* This file is part of JavaPermutationTools (https://jpt.cicirello.org/).
56
*
@@ -74,7 +75,7 @@ public int distance(Permutation p1, Permutation p2) {
7475
for (int i = 0; i < arrayP2.length; i++) {
7576
arrayP2[i] = invP1[p2.get(i)];
7677
}
77-
return countInversions(arrayP2);
78+
return countInversions(arrayP2, 0, arrayP2.length-1);
7879
}
7980

8081
@Override
@@ -83,15 +84,21 @@ public int max(int length) {
8384
return (length*(length - 1))>>1;
8485
}
8586

86-
private int countInversions(int[] array) {
87-
if (array.length <= 1) return 0;
88-
int m = array.length >> 1;
89-
int[] left = Arrays.copyOfRange(array, 0, m);
90-
int[] right = Arrays.copyOfRange(array, m, array.length);
91-
int count = countInversions(left) + countInversions(right);
87+
private int countInversions(int[] array, int first, int last) {
88+
if (last <= first) {
89+
return 0;
90+
}
91+
int m = (first + last) >> 1;
92+
return countInversions(array, first, m) + countInversions(array, m+1, last) + merge(array, first, m+1, last+1);
93+
}
94+
95+
private int merge(int[] array, int first, int midPlus, int lastPlus) {
96+
int[] left = Arrays.copyOfRange(array, first, midPlus);
97+
int[] right = Arrays.copyOfRange(array, midPlus, lastPlus);
9298
int i = 0;
9399
int j = 0;
94-
int k = 0;
100+
int k = first;
101+
int count = 0;
95102
while (i < left.length && j < right.length) {
96103
if (left[i] < right[j]) {
97104
array[k] = left[i];
@@ -117,5 +124,4 @@ private int countInversions(int[] array) {
117124
}
118125
return count;
119126
}
120-
121127
}

0 commit comments

Comments
 (0)