diff --git a/SoSe24/algodat/foundation.py b/SoSe24/algodat/foundation.py index 15ba3fe..48806ca 100644 --- a/SoSe24/algodat/foundation.py +++ b/SoSe24/algodat/foundation.py @@ -328,3 +328,13 @@ def read_int_sequence(filename: str) -> AlgoDatArray: for i in range(len(l)): a[i].value = l[i] return a + +def read_int_sequence_limited(filename: str, limit: int) -> AlgoDatArray: + """Reads a sequence of integers from a file and returns an AlgoDatArray object.""" + with open(filename, "r") as file: + l = list(map(int, file.read().split())) + size = min(len(l), limit) + a = AlgoDatArray(size) + for i in range(size): + a[i].value = l[i] + return a diff --git a/SoSe24/lec03_sort_alg/merge_plot.py b/SoSe24/lec03_sort_alg/merge_plot.py new file mode 100644 index 0000000..4644873 --- /dev/null +++ b/SoSe24/lec03_sort_alg/merge_plot.py @@ -0,0 +1,47 @@ +from SoSe24.algodat.foundation import AlgoDatArray, AlgoDatValue, read_int_sequence, read_int_sequence_limited, MinusInf +import matplotlib.pyplot as plt + + +def merge_sort(z: AlgoDatArray, storage: AlgoDatArray, left: int, right: int): + if left == right: + return + mid = (left + right) // 2 + merge_sort(z, storage, left, mid) + merge_sort(z, storage, mid+1, right) + left_ptr = left + right_ptr = mid+1 + storage_ptr = left + while left_ptr <= mid or right_ptr <= right: + if left_ptr <= mid and right_ptr <= right: + if z[left_ptr] < z[right_ptr]: + storage[storage_ptr].value = z[left_ptr].value + left_ptr += 1 + storage_ptr += 1 + else: + storage[storage_ptr].value = z[right_ptr].value + right_ptr += 1 + storage_ptr += 1 + elif left_ptr <= mid: + storage[storage_ptr].value = z[left_ptr].value + left_ptr += 1 + storage_ptr += 1 + else: + storage[storage_ptr].value = z[right_ptr].value + right_ptr += 1 + storage_ptr += 1 + for i in range(left, right+1): + z[i].value = storage[i].value + + +if __name__ == "__main__": + filename = "../../seq3.txt" + dummy = read_int_sequence("../../seq3.txt") + for right_end in range(1, len(dummy), len(dummy)//100): + AlgoDatValue.reset() + z = read_int_sequence_limited(filename, right_end) + storage = AlgoDatArray(z.size) + merge_sort(z, storage, 0, right_end-1) + plt.plot([right_end], [AlgoDatValue.memory], 'bo') + plt.plot([right_end], [AlgoDatValue.compare], 'ro') + + plt.show() \ No newline at end of file diff --git a/SoSe24/lec03_sort_alg/merge_sort.py b/SoSe24/lec03_sort_alg/merge_sort.py index 7ea3c4a..e8ca997 100644 --- a/SoSe24/lec03_sort_alg/merge_sort.py +++ b/SoSe24/lec03_sort_alg/merge_sort.py @@ -29,7 +29,7 @@ def merge_sort(z: AlgoDatArray, storage: AlgoDatArray, left: int, right: int): storage[storage_ptr].value = z[right_ptr].value right_ptr += 1 storage_ptr += 1 - for i in range(left, right+1): + for i in range(left, right): z[i].value = storage[i].value