Skip to content

Instantly share code, notes, and snippets.

@3-24
Last active September 13, 2018 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3-24/77745f0feb4e275696eadc1a2a0b6c0d to your computer and use it in GitHub Desktop.
Save 3-24/77745f0feb4e275696eadc1a2a0b6c0d to your computer and use it in GitHub Desktop.
user defined list sorting function using divide-and-conquer
def merge(X,left,middle,right): #Assume that left and right part are sorted
A=X[left:middle+1]
B=X[middle+1:right+1]
a,b=len(A),len(B)
i,j=0,0 #i for A, j for B
while (i!=a and j!=b): #compare elements of both part until one reaches end
if A[i]<=B[j]: #right one is bigger
X[left+i+j]=A[i] #Modify X i+j th element as left one
i+=1
else:
X[left+i+j]=B[j]
j+=1
if i!=a: #end of B
for l in range (i,a):
X[left+l+j]=A[l] #add leftover of A
else:
for l in range (j,b):
X[left+l+i]=B[l]
def mergesort(A, left, right): #Modifier Function for 'A"
if right>left: #if len(A[left:right+1])>1. target has more then two values
middle = left + (right-left)/2
mergesort(A,left,middle) #sort left part
mergesort(A,middle+1,right) #sort right part
merge(A,left,middle,right) #merge sorted both part into one.
A=[4,3,2,1]
mergesort(A,0,3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment