Created
November 20, 2012 13:07
-
-
Save hltbra/4117852 to your computer and use it in GitHub Desktop.
mergesort using imutability
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
| # using tail recursion | |
| def merge(l, r, acc): | |
| if not l: | |
| return acc + r | |
| elif not r: | |
| return acc + l | |
| if l[0] < r[0]: | |
| return merge(l[1:], r, acc + [l[0]]) | |
| else: | |
| return merge(l, r[1:], acc + [r[0]]) | |
| def msort(seq): | |
| mid = len(seq) / 2 | |
| if mid == 0: | |
| return seq | |
| else: | |
| left = msort(seq[:mid]) | |
| right = msort(seq[mid:]) | |
| return merge(left, right, []) | |
| # no tail recursion | |
| def merge(l, r): | |
| if not l: | |
| return r | |
| elif not r: | |
| return l | |
| if l[0] < r[0]: | |
| return [l[0]] + merge(l[1:], r) | |
| else: | |
| return [r[0]] + merge(l, r[1:]) | |
| def msort(seq): | |
| mid = len(seq) / 2 | |
| if mid == 0: | |
| return seq | |
| else: | |
| left = msort(seq[:mid]) | |
| right = msort(seq[mid:]) | |
| return merge(left, right) | |
| print(msort([3, 1, 2, 0, 4, -1])) | |
| # [-1, 0, 1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment