Skip to content

Instantly share code, notes, and snippets.

@metula
Created December 18, 2013 21:52
Show Gist options
  • Save metula/8030475 to your computer and use it in GitHub Desktop.
Save metula/8030475 to your computer and use it in GitHub Desktop.
def merge(lst1, lst2):
""" merging two ordered lists using
the two pointer algorithm """
n1 = len(lst1)
n2 = len(lst2)
lst3 = [0 for i in range(n1 + n2)] # alocates a new list
i = j = k = 0 # simultaneous assignment
while (i < n1 and j < n2):
if (lst1[i] <= lst2[j]):
lst3[k] = lst1[i]
i = i +1
else:
lst3[k] = lst2[j]
j = j + 1
k = k + 1 # incremented at each iteration
lst3[k:] = lst1[i:] + lst2[j:] # append remaining elements
return lst3
def mergesort(lst):
""" recursive mergesort """
n = len(lst)
if n <= 1:
return lst
else:
# two recursive calls
return merge(mergesort(lst[0:n//2]), mergesort(lst[n//2:n]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment