File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ def merge (S1 , S2 , S ):
2+ """Merge 2 sorted python lists S1 and S2 into a properly sized list S"""
3+
4+ i = 0
5+ j = 0
6+
7+ while i + j < len (S ):
8+ if j == len (S1 ) or (i < len (S1 ) and S1 [i ] < S2 [j ]):
9+ S [i + j ] = S1 [i ] # copy ith element of S1 as next item of S
10+ i += 1
11+ else :
12+ S [i + j ]= S2 [j ] # copy jth element of S2 as next item of S
13+ j += 1
14+
15+ def merge_sort (S ):
16+ """Sort the elements of S using the merge-sort algorithm"""
17+
18+ n = len (S )
19+ if n < 2 :
20+ return
21+
22+ #divide
23+ mid = n // 2
24+
25+ S1 = S [0 :mid ] #copy first half
26+ S2 = S [mid : n ] #copy second half
27+
28+ #conquer
29+ merge_sort (S1 ) # sort copy of first half
30+ merge_sort (S2 ) # sort copy of second half
31+
32+ #merge results
33+
34+ merge (S1 , S2 , S ) #merge sorter halves back into S
You can’t perform that action at this time.
0 commit comments