Skip to content

Instantly share code, notes, and snippets.

@wnoizumi
Last active October 15, 2015 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wnoizumi/0e1f7e4553de469b7086 to your computer and use it in GitHub Desktop.
Save wnoizumi/0e1f7e4553de469b7086 to your computer and use it in GitHub Desktop.
Java implementation to find the number of inversions in a given array.
public class Inversions {
public static long calcInversions(int[] input) {
if (input.length == 1) {
return 0;
}
long numberOfInversions = 0;
int halfLength = input.length / 2;
int leftLength = halfLength;
int rightLength = halfLength;
if (input.length % 2 != 0) {
leftLength = halfLength + 1;
}
int[] leftHalf = new int[leftLength];
int[] rightHalf = new int[rightLength];
for (int i = 0; i < leftLength; i++) {
leftHalf[i] = input[i];
}
for (int i = leftLength, j = 0; i < input.length; i++, j++) {
rightHalf[j] = input[i];
}
numberOfInversions += calcInversions(leftHalf);
numberOfInversions += calcInversions(rightHalf);
numberOfInversions += merge(leftHalf, rightHalf, input);
return numberOfInversions;
}
private static long merge(int[] leftHalf, int[] rightHalf, int[] output) {
int i = 0;
int j = 0;
int outIndex = 0;
long numberOfInversions = 0;
while (outIndex < output.length) {
if (j >= rightHalf.length || (i < leftHalf.length && leftHalf[i] < rightHalf[j])) {
output[outIndex] = leftHalf[i];
i++;
} else {
output[outIndex] = rightHalf[j];
j++;
numberOfInversions += leftHalf.length - i;
}
outIndex++;
}
return numberOfInversions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment