Review Merge-Lösung und Vergleichsplot

This commit is contained in:
Oliver Hofmann 2026-05-01 06:58:17 +02:00
parent 7352149e2e
commit f0b82e726a
2 changed files with 49 additions and 2 deletions

View File

@ -0,0 +1,47 @@
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
import matplotlib.pyplot as plt
from utils.algo_context import AlgoContext
from utils.algo_array import Array
from vorlesung.L03_fortgeschrittenes_sortieren.quick_sorting import quick_sort
from vorlesung.L03_fortgeschrittenes_sortieren.heap_sorting import heap_sort
from merge_sorting import merge_sort
SIZES = list(range(10, 210, 10))
algorithms = [
("Quicksort", quick_sort),
("Heapsort", heap_sort),
("Merge Sort", merge_sort),
]
comparisons = {name: [] for name, _ in algorithms}
writes = {name: [] for name, _ in algorithms}
for name, sort_func in algorithms:
ctx = AlgoContext()
for n in SIZES:
ctx.reset()
z = Array.random(n, -1000, 1000, ctx)
sort_func(z, ctx)
comparisons[name].append(ctx.comparisons)
writes[name].append(ctx.writes)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
for name in comparisons:
ax1.plot(SIZES, comparisons[name], label=name, marker='o', markersize=3)
ax1.set_ylabel("Vergleiche")
ax1.set_title("Quicksort vs. Heapsort vs. Merge Sort")
ax1.legend()
for name in writes:
ax2.plot(SIZES, writes[name], label=name, marker='o', markersize=3)
ax2.set_ylabel("Schreibzugriffe")
ax2.set_xlabel("n")
ax2.legend()
plt.tight_layout()
plt.show()

View File

@ -15,9 +15,9 @@ def merge_sort_stepwise(z: Array, ctx: AlgoContext, l=None, r=None, buffer=None)
m = (l + r) // 2
yield from merge_sort_stepwise(z, ctx, l, m, buffer)
yield from merge_sort_stepwise(z, ctx, m + 1, r, buffer)
yield from merge(z, ctx, l, m, r, buffer)
yield from merge(z, l, m, r, buffer)
def merge(z: Array, ctx: AlgoContext, l: int, m: int, r: int, buffer: Array):
def merge(z: Array, l: int, m: int, r: int, buffer: Array):
i, j, k = l, m + 1, l
while i <= m and j <= r:
if z[i] <= z[j]: