diff --git a/.idea/misc.xml b/.idea/misc.xml
index 511c874..5a00040 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -3,5 +3,5 @@
-
+
\ No newline at end of file
diff --git a/app/src/main/java/de/uni_marburg/powersort/ASort.java b/app/src/main/java/de/uni_marburg/powersort/sort/ASort.java
similarity index 78%
rename from app/src/main/java/de/uni_marburg/powersort/ASort.java
rename to app/src/main/java/de/uni_marburg/powersort/sort/ASort.java
index 20c1207..f93c57d 100644
--- a/app/src/main/java/de/uni_marburg/powersort/ASort.java
+++ b/app/src/main/java/de/uni_marburg/powersort/sort/ASort.java
@@ -1,4 +1,4 @@
-package de.uni_marburg.powersort;
+package de.uni_marburg.powersort.sort;
import java.util.Comparator;
import java.util.Stack;
@@ -32,7 +32,7 @@ public class ASort {
int j = extendRunRight(array, comparator, i, n);
// Compute the power of the run
- int power = calculatePower(runs.isEmpty() ? null : runs.peek(), i, j);
+ int power = calculatePower(runs, i, j);
// Merge runs if needed based on power comparison
while (!runs.isEmpty() && power <= runs.peek().power) {
@@ -81,22 +81,29 @@ public class ASort {
}
}
- private static int calculatePower(Run previousRun, int currentStart, int currentEnd) {
- if (previousRun == null) {
- return 0; // First run
+ private static int calculatePower(Stack runs, int currentStart, int currentEnd) {
+ if (runs.isEmpty()) {
+ return 0; // First run always has power 0
}
- int previousSize = previousRun.end - previousRun.start;
- int currentSize = currentEnd - currentStart;
- return (int) (Math.log(previousSize + currentSize) / Math.log(2));
+ Run topRun = runs.peek();
+ int size1 = topRun.end - topRun.start;
+ int size2 = currentEnd - currentStart;
+
+ return Math.max(topRun.power, (int) (Math.log(size1 + size2) / Math.log(2))) + 1;
}
private static void mergeRuns(T[] array, Comparator super T> comparator, Stack runs) {
- Run run2 = runs.pop();
- Run run1 = runs.pop();
+ while (runs.size() > 1) {
+ Run run2 = runs.pop();
+ Run run1 = runs.pop();
- merge(array, comparator, run1.start, run1.end, run2.end);
- runs.push(new Run(run1.start, run2.end, calculatePower(null, run1.start, run2.end)));
+ // Merge runs and recalculate power
+ merge(array, comparator, run1.start, run1.end, run2.end);
+ int newPower = Math.max(run1.power, run2.power) + 1;
+
+ runs.push(new Run(run1.start, run2.end, newPower));
+ }
}
private static void merge(T[] array, Comparator super T> comparator, int lo, int mid, int hi) {
@@ -117,7 +124,7 @@ public class ASort {
}
public static void main(String[] args) {
- Integer[] array = {5, 2, 9, 1, 5, 6, 3, 7, 4, 8};
+ Integer[] array = {0, 1, 2, 3, 4, 5, -5, -4, -3, -2, -1, -10, -9, -8, -7, -6};
System.out.println("Before sorting:");
java.util.Arrays.stream(array).forEach(e -> System.out.print(e + " "));
@@ -127,3 +134,5 @@ public class ASort {
java.util.Arrays.stream(array).forEach(e -> System.out.print(e + " "));
}
}
+
+