Created
January 13, 2014 04:30
-
-
Save zpconn/8394747 to your computer and use it in GitHub Desktop.
This is a very simple implementation of merge sort in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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