Merge sort Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.