Browse Source

Lecture 2

master
Oliver Hofmann 6 months ago
parent
commit
2bf815757f

+ 10
- 0
SoSe24/algodat/foundation.py View File

for i in range(len(l)): for i in range(len(l)):
a[i].value = l[i] a[i].value = l[i]
return a 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

+ 47
- 0
SoSe24/lec03_sort_alg/merge_plot.py View File

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()

+ 1
- 1
SoSe24/lec03_sort_alg/merge_sort.py View File

storage[storage_ptr].value = z[right_ptr].value storage[storage_ptr].value = z[right_ptr].value
right_ptr += 1 right_ptr += 1
storage_ptr += 1 storage_ptr += 1
for i in range(left, right+1):
for i in range(left, right):
z[i].value = storage[i].value z[i].value = storage[i].value





Loading…
Cancel
Save