Merge sort
Merge sort is an efficient sorting algorithm based on the merging operation. This algorithm is a very typical application of the partition method (Divide and Conquer). The ordered Subsequence is merged to obtain a fully ordered sequence, i.e., the order of each subsequence is ordered, and then the sequence of sub-sequences is ordered. If you combine two ordered tables into an ordered table, it is called a 2-way merge.
1. Algorithm Description:
- Divide
- Score of
- Splits the fractional group recursively until it is divided into two pairs of individual element arrays.
- Each of these individual elements is then merged with its pair, and then the pairs are merged with their peers until the entire list is merged in the sort order.
- Governance
- It is easy to combine 2 sorted lists into another sorted list.
- Simply by comparing the headers of each list, remove the smallest to add a new sorted list.
- O (N) operation
2. Algorithm properties:
- Stability
- Algorithm time complexity: O (NLOGN)
3. Code implementation
#Algorithm time complexity O (LOGN)#Recursive#two steps: 1. Splitting 2. Mergingdef_merge (A:list, B:list)list:#Merge two sort tablesc = [] whileLen (a) > 0 andLen (b) >0:ifA[0] <b[0]: C.append (a[0]) A.remove (a[0])Else: C.append (b[0]) B.remove (b[0])ifLen (a) = =0:c+=bElse: C+=areturnCdef_merge_sorted (Nums:list)list:#Won ' t sort in place ifLen (nums) <= 1: returnnums M= Len (nums)//2a=_merge_sorted (nums[:m]) #前半b=_merge_sorted (nums[m:]) #后半return_merge (A, b)#Wrapper Packaging DevicedefMerge_sorted (Nums:list, Reverse=false)list:ImportTime start=time.time ()#Merge SortNums =_merge_sorted (nums)ifreverse:nums= Nums[::-1] t= Time.time ()-StartreturnNums, Len (nums), Tlis= [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]merge_sorted (l, Reverse=False) [0]#Output Results[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Merge sort Python