You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

merge_sort.py 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from SoSe24.algodat.foundation import AlgoDatArray, AlgoDatValue, read_int_sequence, MinusInf
  2. from time import perf_counter as pfc
  3. def merge_sort(z: AlgoDatArray, storage: AlgoDatArray, left: int, right: int):
  4. print(left, right)
  5. if left == right:
  6. return
  7. mid = (left + right) // 2
  8. merge_sort(z, storage, left, mid)
  9. merge_sort(z, storage, mid+1, right)
  10. left_ptr = left
  11. right_ptr = right
  12. storage_ptr = left
  13. print("left: ", end="")
  14. for i in range(left, mid+1):
  15. print(z[i], " ", end="")
  16. print(" right: ", end="")
  17. for i in range(mid+1, right+1):
  18. print(z[i], " ", end="")
  19. while left_ptr <= mid or right_ptr <= right:
  20. if left_ptr <= mid and right_ptr <= right:
  21. print("Beides ", z[left_ptr], " ", z[right_ptr])
  22. if z[left_ptr] < z[right_ptr]:
  23. print(" Genommen: ", z[left_ptr])
  24. storage[storage_ptr] = z[left_ptr]
  25. left_ptr += 1
  26. storage_ptr += 1
  27. else:
  28. print(" Genommen: ", z[right_ptr])
  29. storage[storage_ptr] = z[right_ptr]
  30. right_ptr += 1
  31. storage_ptr += 1
  32. elif left_ptr <= mid:
  33. storage[storage_ptr] = z[left_ptr]
  34. left_ptr += 1
  35. storage_ptr += 1
  36. else:
  37. storage[storage_ptr] = z[right_ptr]
  38. right_ptr += 1
  39. storage_ptr += 1
  40. for i in range(left, right+1):
  41. z[i] = storage[i]
  42. if __name__ == "__main__":
  43. z = read_int_sequence("../../seq0.txt")
  44. start = pfc()
  45. storage = AlgoDatArray(z.size)
  46. AlgoDatValue.summary()
  47. merge_sort(z, storage, 0, z.size-1)
  48. print(z)
  49. print(f"Dauer: {pfc() - start:.4f}s")
  50. AlgoDatValue.summary()