Merge remote-tracking branch 'origin/main'

This commit is contained in:
Daniel Langbein 2024-12-17 16:39:14 +00:00
commit 385082bb8d
Signed by: langfingaz
GPG Key ID: 6C47C753F0823002

View File

@ -32,7 +32,7 @@ public class ASort {
int j = extendRunRight(array, comparator, i, n); int j = extendRunRight(array, comparator, i, n);
// Compute the power of the run // 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 // Merge runs if needed based on power comparison
while (!runs.isEmpty() && power <= runs.peek().power) { while (!runs.isEmpty() && power <= runs.peek().power) {
@ -81,22 +81,29 @@ public class ASort {
} }
} }
private static int calculatePower(Run previousRun, int currentStart, int currentEnd) { private static int calculatePower(Stack<Run> runs, int currentStart, int currentEnd) {
if (previousRun == null) { if (runs.isEmpty()) {
return 0; // First run return 0; // First run always has power 0
} }
int previousSize = previousRun.end - previousRun.start; Run topRun = runs.peek();
int currentSize = currentEnd - currentStart; int size1 = topRun.end - topRun.start;
return (int) (Math.log(previousSize + currentSize) / Math.log(2)); int size2 = currentEnd - currentStart;
return Math.max(topRun.power, (int) (Math.log(size1 + size2) / Math.log(2))) + 1;
} }
private static <T> void mergeRuns(T[] array, Comparator<? super T> comparator, Stack<Run> runs) { private static <T> void mergeRuns(T[] array, Comparator<? super T> comparator, Stack<Run> runs) {
while (runs.size() > 1) {
Run run2 = runs.pop(); Run run2 = runs.pop();
Run run1 = runs.pop(); Run run1 = runs.pop();
// Merge runs and recalculate power
merge(array, comparator, run1.start, run1.end, run2.end); merge(array, comparator, run1.start, run1.end, run2.end);
runs.push(new Run(run1.start, run2.end, calculatePower(null, run1.start, run2.end))); int newPower = Math.max(run1.power, run2.power) + 1;
runs.push(new Run(run1.start, run2.end, newPower));
}
} }
private static <T> void merge(T[] array, Comparator<? super T> comparator, int lo, int mid, int hi) { private static <T> 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) { 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:"); System.out.println("Before sorting:");
java.util.Arrays.stream(array).forEach(e -> System.out.print(e + " ")); 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 + " ")); java.util.Arrays.stream(array).forEach(e -> System.out.print(e + " "));
} }
} }