Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Stefano Nebiolo
1,991 PointsMergeSort python
Hi everybosy. I was doing some extra excercise trying to write down a code for the merge sort. It consist in a divide and conquer algorithm that split a list in two, until having singolar elements and then it sort them merging them together. I wrote a code, but the result I get is just slight different from the input list. I am not understanding where the problem is. Anyone able to help? P.S. don't mind the #comments, I was just plying around
def mergesort(data):
merge sorting of a list (divide and conquer)
res = []
if len(data) < 2:
return data
mid = len(data)//2
#mid = int(len(data)/2)
fst = data[:mid]
snd = data[mid:]
mergesort(fst)
mergesort(snd)
fi = 0
si = 0
k = 0
while fi < len(fst) and si < len(snd):
if fst[fi] < snd[si]:
res.append(fst[fi])
#data.append(fst[fi])
fi += 1
else:
res.append(snd[si])
#data.append(snd[si])
si += 1
k += 1
if fi<len(fst):
res.extend(fst[fi:])
#data.extend(fst[fi:])
elif si<len(snd):
res.extend(snd[si:])
#data.extend(snd[si:])
return res
#return data