Merge sort:
Principle and implementation of C language
Reference: The implementation of the five-merge sort in vernacular classical algorithm series
1. It is easy to sort an ordered array, A and B.
2. In order to make a, B group of data in order: can be a, group B separately divided into two groups.
3. After a continuous grouping, when the divided group has only one data (orderly), merging the adjacent two groups.
This is done by first recursive decomposition of the series, and then merging the sequence to complete the merge sort .
Code excerpt from "Python algorithm"
1 #merging and sorting of array seq2 #returns the sorted array3 defmergesort (seq):4Mid = Len (seq)//25LFT, RGT =Seq[:mid], Seq[mid:]6 ifLen (LFT) > 1:lft = MergeSort (LFT)#sort half of an array7 ifLen (RGT) > 1:RGT =mergesort (RGT)8 9res = []Ten #Lft,rgt are arranged in ascending order One whileLfT andRgt#the left and right arrays are not empty A ifLFT[-1] >= Rgt[-1]:#find the largest element in two arrays -Res.append (Lft.pop ())#into the result array and delete the original array elements - Else: theRes.append (Rgt.pop ())#if pop (0) is used, the following res is not reversed, but the pop (0) time is slow - #and res is relatively fast . - #Res starts with a descending array, which is reversed to increment - Res.reverse () + return(LFTorRGT) + Res#before the rest of the ordered array is spelled to res - +seq = [1,2,4,6,3,7,5,9,0,5,7] A PrintMergeSort (seq)
Python data structure and algorithm--merge sort