1. Code implementation
defMerge_sort (alist):ifLen (alist) <= 1: returnalist#two-part decompositionnum = Len (alist)/2 Left=Merge_sort (Alist[:num]) right=Merge_sort (alist[num:])#Merging returnmerge (Left,right)defmerge (left, right):" "merge operation, combine two ordered arrays left[] and right[] into a large ordered array" " #The subscript pointer to left and rightL, R =0, 0 result= [] whileL<len (left) andr<Len (right):ifLEFT[L] <Right[r]: Result.append (Left[l]) L+ = 1Else: Result.append (Right[r]) R+ = 1result+=left[l:] Result+=Right[r:]returnresultalist= [54,26,93,17,77,31,44,55,20]sorted_alist=mergesort (alist)Print(sorted_alist)
2. Note:
(1) Merge sort adopts the idea of first splitting and merging; recursive split to not continue split stop split, then compare, and finally recursively merge
3. Complexity of Time
Optimal time complexity: O (NLOGN)
Worst time complexity: O (NLOGN)
Stability: Stable
Python data structures and algorithms 13th Day "merge sort"