52 lines
1.7 KiB
Java
52 lines
1.7 KiB
Java
package Presenter.Algorithms;
|
|
|
|
import java.util.List;
|
|
|
|
/**
|
|
* Created by armin on 18.06.17.
|
|
*/
|
|
public class InversionCounter {
|
|
|
|
|
|
/**
|
|
* Angepasster Merge-Sort Algorithmus.
|
|
* Die Funktion bekommt neben den standard Parametern zusätzlich eine Liste mit Elementen
|
|
* die als Groundtruth dienen.
|
|
* @param a Eingabefeld mit den Elementen die überprüft werden sollen.
|
|
* @param start Startpunkt des Eingabefeldes.
|
|
* @param end Endpunkt des Eingabefeldes.
|
|
* @param aux Groundtruth Ordnung um die Anzahl der Inversionen zu bestimmen.
|
|
* @return Anzahl der inversionen zwischen a und aux.
|
|
*/
|
|
public static int run(List<Double> a, int start, int end, List<Double> aux) {
|
|
if (start >= end) {
|
|
return 0;
|
|
}
|
|
int invCount = 0;
|
|
int mid = start + (end - start) / 2;
|
|
int invCountLeft = run(a, start, mid, aux); // divide and conquer
|
|
int invCountRight = run(a, mid + 1, end, aux); // divide and conquer
|
|
invCount += (invCountLeft + invCountRight);
|
|
for (int i = start; i <= end; i++) {
|
|
aux.set(i, a.get(i));
|
|
}
|
|
int left = start;
|
|
int right = mid + 1;
|
|
int index = start;
|
|
while (left <= mid && right <= end) {
|
|
if (aux.get(left) < aux.get(right)) {
|
|
a.set(index++, aux.get(left++));
|
|
} else {
|
|
a.set(index++, aux.get(right++));
|
|
invCount += mid - left + 1; // number of inversions for aux[right]
|
|
}
|
|
}
|
|
while (left <= mid) {
|
|
a.set(index++, aux.get(left++));
|
|
}
|
|
// no need to copy over remaining aux[right++] because they are already inside a
|
|
return invCount;
|
|
}
|
|
|
|
}
|