I couldn’t find any working Python 3.3 mergesort algorithm codes, so I made one myself. Is there any way to speed it up? It sorts 20,000 numbers in about 0.3-0.5 seconds
JavaScript
x
25
25
1
def msort(x):
2
result = []
3
if len(x) < 2:
4
return x
5
mid = int(len(x)/2)
6
y = msort(x[:mid])
7
z = msort(x[mid:])
8
while (len(y) > 0) or (len(z) > 0):
9
if len(y) > 0 and len(z) > 0:
10
if y[0] > z[0]:
11
result.append(z[0])
12
z.pop(0)
13
else:
14
result.append(y[0])
15
y.pop(0)
16
elif len(z) > 0:
17
for i in z:
18
result.append(i)
19
z.pop(0)
20
else:
21
for i in y:
22
result.append(i)
23
y.pop(0)
24
return result
25
Advertisement
Answer
You can initialise the whole result list in the top level call to mergesort:
JavaScript
1
3
1
result = [0]*len(x) # replace 0 with a suitable default element if necessary.
2
# or just copy x (result = x[:])
3
Then for the recursive calls you can use a helper function to which you pass not sublists, but indices into x
. And the bottom level calls read their values from x
and write into result
directly.
That way you can avoid all that pop
ing and append
ing which should improve performance.