This is my version of mergesort.
# mergesort
def merge(items, low, mid, high):
left = [items[i] for i in range(low, mid + 1)]
right = [items[i] for i in range(mid + 1, high + 1)]
left.append(4444444444444444444444)
right.append(4444444444444444444444)
i = 0
j = 0
for k in range(low, high + 1):
if left[i] < right[j]:
items[k] = left[i]
i += 1
else:
items[k] = right[j]
j += 1
def mergesort(items,low, high):
mid = int(low + (high - low) / 2)
if low < high:
mergesort(items, low, mid)
mergesort(items, mid + 1, high)
merge(items, low, mid, high)
if __name__ == "__main__":
a = [6, 5, 4, 3, 2, 1]
print(mergesort(a, 0, len(a) - 1))
I ran a test with input size of 1000000 in reverse order with a step of 1 i.e range(int(1e6), 1, -1)
or range(1000000, 1, -1)
and got the following results
6999991 function calls (4999995 primitive calls) in 9.925 seconds
Ordered by: internal time
List reduced from 9 to 8 due to restriction <8>
ncalls tottime percall cumtime percall filename:lineno(function)
999998 6.446 0.000 8.190 0.000 test.py:3(merge)
1999997/1 1.735 0.000 9.925 9.925 test.py:19(mergesort)
999998 0.821 0.000 0.821 0.000 test.py:4(<listcomp>)
999998 0.740 0.000 0.740 0.000 test.py:5(<listcomp>)
1999996 0.183 0.000 0.183 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 9.925 9.925 {built-in method builtins.exec}
1 0.000 0.000 9.925 9.925 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {built-in method builtins.len}
I would love to optimize the code and if possible, eliminate the copies.
int
that isrange(int(ie6), 1, -1)
or rather userange(1000000, 1 -1)
\$\endgroup\$