Skip to content

Commit caf424f

Browse files
committed
Add py merge sort
1 parent 89e69c4 commit caf424f

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

python/main.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,21 @@
1818
A = [5, 2, 4, 6, 1, 3] # cf. Figure 2.2, p. 18
1919
insertion_sort(A)
2020
print('\nsorted:', A)
21+
22+
A = [31, 41, 59, 26, 41, 58] # cf. Exercise 2.1-1, p. 22
23+
insertion_sort(A)
24+
print('\nsorted:', A)
25+
26+
# CLRS Section 2.3 - Merge Sort
27+
from sorting.p034_merge_sort import merge_sort
28+
A = []
29+
30+
print('\nSection 2.3 - Merge Sort')
31+
32+
A = [2, 4, 5, 7, 1, 2, 3, 6] # cf. Figure 2.3, p. 32
33+
merge_sort(A, 0, len(A)-1)
34+
print('\nsorted:', A)
35+
36+
A = [3, 41, 52, 26, 38, 57, 9, 49] # cf. Exercise 2.3-1, p. 37
37+
merge_sort(A, 0, len(A)-1)
38+
print('\nsorted:', A)

python/sorting/p034_merge_sort.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''
2+
CLRS Section 2.3, p. 34
3+
'''
4+
import math
5+
6+
def merge(A, p, q, r):
7+
n1 = q - p + 1
8+
n2 = r - q
9+
L = [None for element in range(0, n1 + 1)]; R = [None for element in range(0, n2 + 1)]
10+
for i in range(0, n1):
11+
L[i] = A[p + i]
12+
for j in range(0, n2):
13+
R[j] = A[q + j + 1]
14+
L[n1] = math.inf
15+
R[n2] = math.inf
16+
i = 0
17+
j = 0
18+
for k in range(p, r + 1):
19+
if L[i] <= R[j]:
20+
A[k] = L[i]
21+
i += 1
22+
else:
23+
A[k] = R[j]
24+
j += 1
25+
26+
def merge_sort(A, p, r):
27+
if p < r:
28+
q = (p + r)//2
29+
merge_sort(A, p, q)
30+
merge_sort(A, q + 1, r)
31+
merge(A, p, q, r)

0 commit comments

Comments
 (0)