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:
- 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.
- 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.
- 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.
- 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