I’ve implemented what I believe to be a merge sort algorithm in python. I’ve never programmed in Python before, so I used several resources with commands that seemed foreign to me, to gain a better understanding.
However, I’ve also never implemented merge sort in the first place, so I’m not sure if I’ve even implemented it correctly. Any guidance, tips, or corrections would be greatly appreciated.
Here is my merge method:
def merge(left, right):
result = []
i, j = 0, 0
while(i < len(left) and j< len(right)):
if(len(left[i]) <= len(right[j])):
print(i)
result.append(left[i])
i=i+1
else:
result.append(right[j])
j=j+1
result += left[i:]
result += right[j:]
return result
meanwhile, here is my mergesort method:
def mergesort(list):
if len(list) < 2:
return list
else:
middle = len(list) / 2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
Thanks for any possible help! 🙂
Don’t name variables “list”. That’s the name of Python’s array type, so using a variable by the same name is confusing.
When you return from a conditional, you don’t need to sitck the rest of the function in an else block.
Overall, it looks reasonable.
Of course, for anything but an exercise, you should be using list.sort or sorted().