Skip to content
This repository was archived by the owner on Nov 4, 2024. It is now read-only.

Commit c3e12c4

Browse files
Create merge_sort.py
1 parent 384b79a commit c3e12c4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

sorting/merge_sort.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
# author: bt3gl
4+
5+
6+
def merge_sort(array):
7+
8+
# part 1: recursively divide the array into subarrays
9+
if len(array) < 2:
10+
return array
11+
12+
mid = len(array) // 2
13+
left = merge_sort(array[:mid])
14+
right = merge_sort(array[mid:])
15+
16+
# part 2: merge the subarrays
17+
result = []
18+
i, j = 0, 0
19+
20+
while i < len(left) and j < len(right):
21+
if left[i] <= right[j]:
22+
result.append(left[i])
23+
i +=1
24+
else:
25+
result.append(right[j])
26+
j +=1
27+
28+
if left[i:]:
29+
result.extend(left[i:])
30+
if right[j:]:
31+
result.extend(right[j:])
32+
33+
return result
34+

0 commit comments

Comments
 (0)