diff --git a/praktika/02_merge_sort/compare_sorts.py b/praktika/02_merge_sort/compare_sorts.py new file mode 100644 index 0000000..c9060e0 --- /dev/null +++ b/praktika/02_merge_sort/compare_sorts.py @@ -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() \ No newline at end of file diff --git a/praktika/02_merge_sort/merge_sorting.py b/praktika/02_merge_sort/merge_sorting.py index 57f6c25..f91983e 100644 --- a/praktika/02_merge_sort/merge_sorting.py +++ b/praktika/02_merge_sort/merge_sorting.py @@ -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]: