Skip to content

Instantly share code, notes, and snippets.

@kbendick
Created March 8, 2016 20:11
Show Gist options
  • Save kbendick/37c6ca5f18fbe3255e8b to your computer and use it in GitHub Desktop.
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)
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