Created
March 8, 2016 20:11
-
-
Save kbendick/37c6ca5f18fbe3255e8b to your computer and use it in GitHub Desktop.
Merge sort using indexing into arrays to run in O(n log n)
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 mergesort(L): | |
return L if len(L) < 2 else merge(mergesort(L[:len(L)/2]), mergesort(L[len(L)/2:])) | |
def merge(A,B): | |
Out = [] | |
iA = iB = 0 | |
while len(A)+len(B) > iA + iB: | |
if len(B) <= iB or (len(A) > iA and A[iA] < B[iB]): | |
Out.append(A[iA]) | |
iA = iA + 1 | |
else: | |
Out.append(B[iB]) | |
iB = iB + 1 | |
return Out | |
print mergesort([3,4,1,5,9,2,6,5,3,5]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment