Here are the basic algorithm about merge sort:
defmerge (s1,s2,s): I=j=0 whilei + J <Len (s):ifj = = Len (s2)or(I < Len (S1) andS1[i] <S2[j]): S[i+ j] =S1[i] I+ = 1Else: S[i+ j] =S2[j] J+ = 1defMerge_sort (s):"""Sort The elements of Python list s using Merge-sort algorithm""" #Time Compelxity:o (NLOGN), where n = Len (s)n =Len (s)ifN < 2: return #DivideMID = N//2S1=S[:mid] S2=S[mid:]#Conquer (with recursion)Merge_sort (S1) merge_sort (S2)#Merge Resultsmerge (S1,s2,s)
Insertion sort:time Complexity:o (n^2)
defInsertion_sort (A): "" "sort list of comparable elements into nondecreasing order." " forKinchRange (1, Len (A)):#From 1 to n-1cur = a[k]#Current element to be insertedj = k#find correct index j for current whileJ > 0 andA[j-1] > Cur:#element A[j-1] must is after currentA[J] = a[j-1] J-= 1A[j]= cur#cur is now on the right place
[Building block] Merge sort @ Python