Merge sort with Python

Source: Internet
Author: User

defMerge (Lfrom, LTO, Low, Mid, high): I, J, K=Low, Mid, low whileI<Mid andJ<HighifLfrom[i]<LFROM[J]: lto[k]=Lfrom[i] I+= 1        Else: Lto[k]=LFROM[J] J+= 1K+= 1     whileI<MID:LTO[K]=Lfrom[i] I+= 1K+= 1     whileJ<HIGH:LTO[K]=LFROM[J] J+= 1K+= 1defMerge_pass (Lfrom, LTO, Llen, Slen): I= 0     whileI+2*Slen<Llen:merge (Lfrom, LTO, I, I+Slen, I+2*Slen) I+= 2*SlenifI+Slen<Llen:merge (Lfrom, LTO, I, I+Slen, Llen)Else: forJinch Range(I, Llen): Lto[j]=LFROM[J]defMerge_sort (LST): Slen, Llen= 1,Len(LST) templist=[None]*Llen whileSlen<Llen:merge_pass (LST, templist, Llen, Slen) slen*= 2Merge_pass (Templist, LST, Llen, Slen) slen*= 2

The idea of merging sorts is:

    1. In contrast to the quick sort from the long sequence to the short sequence, the merge sort is preceded by a short line, followed by a platoon leader.
    2. For a sequence, the first view is that each element is a sequence, 22 merges. For each "22 merge", it is the process of merging two sequential sequences.
    3. The merge sort needs to open up space as large as the original sequence. The result of merging is put into the open space. The second merger is to merge the new space into the old space, so that the sequence is sorted out so repeatedly.
    4. The implementation is divided into three tiers:
    • Lowest level: Merges two sorted sequences
    • Intermediate level: Merges the entire sequence, depending on the length of the subsequence, respectively
    • Highest level: Multiply the subsequence length from 1 until the subsequence length is the same as the sequence length, and the merge is complete.

Merge sort with Python

Related Article

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.