I have here a code for sorting lists using merge sort.. I just got it somewhere in the net.. But honestly, I can’t follow the flow of the code… I mean, I can’t get how it is implemented. I can understand some part especially the first one where it divides the entire list in two and then sort each side of the list. And then what?? Will you please tell what’s happening here? Thank you. 🙂
def merge(badlist):
if len(badlist) == 1:
return badlist
m = len(badlist)/2
l = merge(badlist[:m])
r = merge(badlist[m:])
if not len(l) or not len(r):
return l or r
result = []
i = j = 0
while (len(result) < len(r) + len(l)):
if l[i] < r[j]:
result.append(l[i])
i += 1
else:
result.append(r[j])
j += 1
if i == len(l) or j == len(r):
result.extend(l[i:] or r[j:])
break
return result
print merge(badlist)
Going line by line,
This checks whether either of the lists is empty. If it is, then the other list is returned.
Here,
resultandi,jare initializedRuns the
whileloop till all elements of both lists have been copied to theresultlist.This block checks which of
l[i]orr[j]is lesser and then appends it toresult, and advances the respective counter. This goes on till either of the lists gets completely used up, which is checked for in the following code block :Now, whichever list still contains elements, is appended to the end of
resultlist as is.After which
resultis returned.As mentioned, the indentation is incorrect in your sample, which I have corrected here.