Your function mergesort returns a new list, and does not modify the one you supplied it, as you seem to expect it to be doing. So when you call mergesort(a[:mid]) for example, what you get back is a new sorted version of those elements, while the original a[:mid] stays exactly the same.
EDIT: The issue here is the way python list slicing works. When you say a[:mid], python creates a 'copy' ( let's not worry about the exact type of copy ) of the original. Now when you modify this copy in a function, all you're doing is changing the references in it to point to new integers, not modifying the original in any way. Here's some code to flesh this out:
def change(a):
a[1] = 0
a = [1, 2, 3]
change(a)
a
>> [1, 0, 3]
a = [1, 2, 3]
change(a[:2])
a
>> [1, 2, 3]
EDIT 2: Copying back the values done correctly (as suggested by (abamert) in the comments):
def mergesort(a):
if len(a)<=1:
return a
else:
mid=len(a)/2
a = mergesort(a[:mid]) + mergesort(a[mid:])
auxa=[]
j=0
k=mid
while j<mid and k<len(a):
if a[j]<a[k]:
auxa.append(a[j])
j+=1
else:
auxa.append(a[k])
k+=1
if j==mid:
auxa.extend(a[k:])
if k==len(a):
auxa.extend(a[j:mid])
return auxa
This are obviously better ways to do this with less copying involved, but I think this solution is slightly more relevant to the issue with the original code.
mergesort()calls