Files
tira/viikko3/merge-sort.py
T
2023-11-07 01:27:43 +02:00

50 lines
862 B
Python

from random import shuffle
from time import time
n = 10**5
randList = [x for x in range(1, n + 1)]
helper_list = [0 for x in range(n + 1)]
shuffle(randList)
def main():
a = 0
b = len(randList) - 1
start_time = time()
sort(a, b)
end_time = time()
final_time = end_time - start_time
print(final_time, "s")
def sort(a, b):
if a == b:
return
k = (a + b) // 2
sort(a, k)
sort(k + 1, b)
merge(a, k, k + 1, b)
def merge(a1, b1, a2, b2):
a = a1
b = b2
for x in range(a, b + 1):
if a2 > b2 or (a1 <= b1 and randList[a1] <= randList[a2]):
helper_list[x] = randList[a1]
a1 += 1
else:
helper_list[x] = randList[a2]
a2 += 1
for x in range(a, b + 1):
randList[x] = helper_list[x]
if __name__ == "__main__":
main()