Created
February 10, 2013 00:41
-
-
Save cabiad/4747785 to your computer and use it in GitHub Desktop.
Quick code kata, a merge sort in Python. Completed first on whiteboard, manually tested there, then re-tested by typing and running it through the interpreter.
This file contains hidden or 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
#################################### | |
# Copyright Christopher Abiad, 2012 | |
# All Rights Reserved | |
#################################### | |
__author__ = 'Christopher Abiad' | |
def mergesort(l): | |
n = len(l) | |
if n <= 1: | |
return l | |
return merge(mergesort(l[:n/2]), mergesort(l[n/2:])) | |
def merge(l1, l2): | |
result = [] | |
i1 = 0 | |
i2 = 0 | |
while i1 < len(l1) and i2 < len(l2): | |
if l1[i1] <= l2[i2]: | |
result.append(l1[i1]) | |
i1 += 1 | |
else: | |
result.append(l2[i2]) | |
i2 += 1 | |
if i1 < len(l1): | |
result.extend(l1[i1:]) | |
else: | |
result.extend(l2[i2:]) | |
return result | |
# Test code follows | |
from pprint import pprint | |
if __name__ == '__main__': | |
pprint(mergesort([3,4,1,9])) | |
pprint(mergesort([86,7,5,30,9])) | |
pprint(mergesort([1,2,3,4,5])) | |
pprint(mergesort([5,4,3,2])) | |
pprint(mergesort([1])) | |
pprint(mergesort([])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment