Hello,
I am getting unexpected(?) results from this mergesort implementation. It's extremely slow compared to my three-way quicksort(also written in python).
My quicksort finishes with 10000 elements after about 0.005s while mergesort needs 1.6s! Including the source code for both implementations.
Mergesort:
#Merges two sorted lists into one sorted list. recursively
def merge(left, right):
if len(left) == 0 and len(right) == 0:
return []
elif len(left) == 0:
return right
elif len(right) == 0:
return left
else:
if left[0] <= right[0]:
return left[:1] + merge(left[1:],right)
else:
return right[:1] + merge(left,right[1:])
#Splits a list in half and returns the halves
def halve(list):
return list[:len(list)//2],list[len(list)//2:]
#Mergesort
def mergesort(list):
if len(list) <= 1:
return list
left,right = halve(list)
left,right = mergesort(left),mergesort(right)
return merge(left,right)
Quicksort:
#Three-way QuickSort in Python
def quicksort(a):
if len(a) == 0:
return []
p = a[(len(a)-1)//2]
less = quicksort([x for x in a if x < p])
greater = quicksort([x for x in a if x > p])
equal = [x for x in a if x == p]
return less + equal + greater
Can someone come up with an explanation or maybe even a fix?