Skip to content

Instantly share code, notes, and snippets.

@zpconn
Created January 13, 2014 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zpconn/8394747 to your computer and use it in GitHub Desktop.
Save zpconn/8394747 to your computer and use it in GitHub Desktop.
This is a very simple implementation of merge sort in Python.
def merge(a1, a2):
res = []
i = 0
j = 0
while i < len(a1) and j < len(a2):
if a1[i] < a2[j]:
res.append(a1[i])
i += 1
else:
res.append(a2[j])
j += 1
res += a1[i:]
res += a2[j:]
return res
def mergesort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) / 2
first_half = arr[0:mid]
second_half = arr[mid:len(arr)]
return merge(mergesort(first_half), mergesort(second_half))
print mergesort([3, 5, 4, 3, 6, 7, 8, 6, 4, 5])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment