Fixed FinnSort: Cleared runs for every method call

This commit is contained in:
finnm 2024-12-16 22:50:51 +01:00
parent fa70412791
commit e182ecc756

View File

@ -5,10 +5,12 @@ import static java.lang.Math.*;
public class FinnSort { public class FinnSort {
private static final ArrayList<Run> runs = new ArrayList<>(); private static ArrayList<Run> runs;
public static <T> void sort(T[] a, Comparator<? super T> c) { public static <T> void sort(T[] a, Comparator<? super T> c) {
runs = new ArrayList<>();
int n = a.length; int n = a.length;
int i = 0; int i = 0;
int j = extendRunRight(a, i, c); int j = extendRunRight(a, i, c);
@ -42,14 +44,22 @@ public class FinnSort {
ArrayList<T> run2 = new ArrayList<>(Arrays.asList(a).subList(r2.start, r2.end)); ArrayList<T> run2 = new ArrayList<>(Arrays.asList(a).subList(r2.start, r2.end));
ArrayList<T> merge = new ArrayList<>(); ArrayList<T> merge = new ArrayList<>();
while (!run1.isEmpty() || !run2.isEmpty()) { while (!run1.isEmpty() && !run2.isEmpty()) {
if (run2.isEmpty() || !run1.isEmpty() && c.compare(run1.getFirst(), run2.getFirst()) < 0) { if (c.compare(run1.getFirst(), run2.getFirst()) < 0) {
merge.add(run1.removeFirst()); merge.add(run1.removeFirst());
} else { } else {
merge.add(run2.removeFirst()); merge.add(run2.removeFirst());
} }
} }
while (!run1.isEmpty()) {
merge.add(run1.removeFirst());
}
while (!run2.isEmpty()) {
merge.add(run2.removeFirst());
}
System.arraycopy(merge.toArray(), 0, a, min(r1.start, r2.start), merge.size()); System.arraycopy(merge.toArray(), 0, a, min(r1.start, r2.start), merge.size());
Run r = new Run(min(r1.start, r2.start), max(r1.end, r2.end), min(r1.power, r2.power)); Run r = new Run(min(r1.start, r2.start), max(r1.end, r2.end), min(r1.power, r2.power));
runs.add(r); runs.add(r);