Skip to content

Commit 1b0d751

Browse files
committed
mergeSort
1 parent d8b880f commit 1b0d751

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

array_mergeSort.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
def mergeSort(arr):
2+
if len(arr) == 1:
3+
return arr
4+
5+
middle = len(arr) // 2
6+
left = arr[:middle]
7+
right = arr[middle:]
8+
9+
left_result = mergeSort(left)
10+
right_result = mergeSort(right)
11+
12+
return merge(left_result, right_result)
13+
14+
15+
def merge(left_result, right_result):
16+
result = [None] * (len(left_result) + len(right_result))
17+
i = j = k = 0
18+
while i < len(left_result) and j < len(right_result):
19+
if left_result[i] <= right_result[j]:
20+
result[k] = left_result[i]
21+
i += 1
22+
else:
23+
result[k] = right_result[j]
24+
j += 1
25+
k += 1
26+
27+
while i < len(left_result):
28+
result[k] = left_result[i]
29+
i += 1
30+
k += 1
31+
32+
while j < len(right_result):
33+
result[k] = right_result[j]
34+
j += 1
35+
k += 1
36+
37+
return result
38+
39+
40+
arr = [50, 40, 30, 20, 10]
41+
print(arr)
42+
print('sorted array:')
43+
print(mergeSort(arr))
44+

0 commit comments

Comments
 (0)