Skip to content

Instantly share code, notes, and snippets.

@nsfyn55
Last active December 18, 2015 19:19
Show Gist options
  • Save nsfyn55/5832065 to your computer and use it in GitHub Desktop.
Save nsfyn55/5832065 to your computer and use it in GitHub Desktop.
Python Merge Sort
def merge(l1, l2):
result = []
pos_left = 0
pos_right = 0
for i in range(len(l1) + len(l2)):
if(pos_left >= len(l1)):
result = result + l2[pos_right:len(l2)]
break
if(pos_right >= len(l2)):
result = result + l1[pos_left:len(l1)]
break
elif(l1[pos_left] <= l2[pos_right]):
result.append(l1[pos_left])
pos_left = pos_left + 1
elif(l2[pos_right] <= l1[pos_left]):
result.append(l2[pos_right])
pos_right = pos_right + 1
return result
def split(l):
length = len(l)
split_on = length/2
if(length == 1):
return l
else:
left = split(l[0:split_on])
right = split(l[split_on:length])
return merge(left, right)
l = [1, 1, 4, 15, 18, 7, 9, 2, 18]
print split(l)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment