Skip to content

Commit b9a3e2c

Browse files
committed
solved: practice #2 merge_sort algorithm -@iamserda
1 parent 5a72783 commit b9a3e2c

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import math, random
2+
3+
4+
def merge_sort(arr):
5+
"""sorts an array, in ascending order"""
6+
if not arr:
7+
print(ValueError("List is empty. Cannot sort an empty list."))
8+
return []
9+
10+
if len(arr) == 1:
11+
return arr
12+
else:
13+
mid = int(math.ceil(len(arr) / 2))
14+
arr1 = merge_sort(arr[:mid])
15+
arr2 = merge_sort(arr[mid:])
16+
arr3 = merge_sorted_arrays(arr1, arr2)
17+
return arr3
18+
19+
20+
def merge_sorted_arrays(sorted_arr1, sorted_arr2):
21+
sorted_arr3 = []
22+
i = 0
23+
j = 0
24+
while True:
25+
if i >= len(sorted_arr1) and j >= len(sorted_arr2):
26+
return sorted_arr3
27+
28+
if i < len(sorted_arr1) and j >= len(sorted_arr2):
29+
sorted_arr3.append(sorted_arr1[i])
30+
i += 1
31+
continue
32+
33+
if j < len(sorted_arr2) and i >= len(sorted_arr1):
34+
sorted_arr3.append(sorted_arr2[j])
35+
j += 1
36+
continue
37+
38+
if sorted_arr1[i] <= sorted_arr2[j]:
39+
sorted_arr3.append(sorted_arr1[i])
40+
i += 1
41+
continue
42+
43+
if sorted_arr1[i] > sorted_arr2[j]:
44+
sorted_arr3.append(sorted_arr2[j])
45+
j += 1
46+
continue
47+
break
48+
return sorted_arr3
49+
50+
51+
# Testing Arenas:
52+
53+
arr = [random.randint(-10, 10) for i in range(10)]
54+
print("before:", arr)
55+
sorted_arr = merge_sort(arr)
56+
sorted_arr_prime = sorted(arr)
57+
assert sorted_arr == sorted_arr_prime
58+
print("after:", sorted_arr)

0 commit comments

Comments
 (0)