merge Sort execution process:
1, the implementation of the merge sorting function, the total number of two in two, continue to call the function itself recursively, left half right half of the division open, until only one element in each copy, stop dividing.
2, the divided elements in the order of size, first 1 1, merged into an array of 2, and then 2 2 in order size required to merge into an array of 4, followed by sorting all the elements by size
22 Both sequences are ordered sequences when merging
such as:
4 1 3 7 3 5 0
4 1 3 7 3 5 0
4 1 3 7 3 5 0
4 1 3 10 7 3 5 0//The number of each group is 1 end
Consolidation: 1 4 3 3 7 0 5
1 3 4 0 3 5 7
Final Result: 0 1 3 3 4 5 7 10
target sequence: L = [1000, 5, 6, 7, 3, 30, 25, 12, 9, 13, 10, 8]
defMergeSort (left, Mid, right): L_1, l_2=L[left:mid], L[mid:right]Print("before merging:", L_1, l_2) len1=Len (l_1) Len2=Len (l_2) A, B, L3=0, 0, [] whileA < Len1 andb <Len2:ifL_1[a] <=L_2[b]: L3.append (L_1[a]) a+ = 1Else: L3.append (l_2[b]) b+ = 1 whileA <len1:l3.append (L_1[a]) a+ = 1 whileb <len2:l3.append (l_2[b]) b+ = 1L[left:right]=l3[:]Print("after:", L)defSor (left, right):ifLeft <Right:mid= Int (left + right)/2) Sor (left, mid) Sor (Mid+1, right) MergeSort (left, mid+1, right+1) sor (0,11)Print("\ n Complete:"L
Execution process
Before merging: [1000] [5] After: [5, 1000, 6, 7, 3, 30, 25, 12, 9, 13, 10, 8] Before merging: [5, 1000] [6] After: [5, 6, 1000, 7, 3, 30, 25, 12, 9, 13, 10, 8] Before merging: [7] [3] After: [5, 6, 1000, 3, 7, 30, 25, 12, 9, 13, 10, 8] Before merging: [3, 7] [30] After: [5, 6, 1000, 3, 7, 30, 25, 12, 9, 13, 10, 8] Before merging: [5, 6, 1000] [3, 7, 30] After: [3, 5, 6, 7, 30, 1000, 25, 12, 9, 13, 10, 8] Before merging: [25] [12] After: [3, 5, 6, 7, 30, 1000, 12, 25, 9, 13, 10, 8] Before merging: [12, 25] [9] After: [3, 5, 6, 7, 30, 1000, 9, 12, 25, 13, 10, 8] Before merging: [13] [10] After: [3, 5, 6, 7, 30, 1000, 9, 12, 25, 10, 13, 8] Before merging: [10, 13] [8] After: [3, 5, 6, 7, 30, 1000, 9, 12, 25, 8, 10, 13] Before merging: [9, 12, 25] [8, 10, 13] After: [3, 5, 6, 7, 30, 1000, 8, 9, 10, 12, 13, 25] Before merging: [3, 5, 6, 7, 30, 1000] [8, 9, 10, 12, 13, 25] After: [3, 5, 6, 7, 8, 9, 10, 12, 13, 25, 30, 1000] Complete: [3, 5, 6, 7, 8, 9, 10, 12, 13, 25, 30, 1000]process finished with exit code 0
Python implements merge sort