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.4KB

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