8000 Add mergesort · AllAlgorithms/python@f7f877b · GitHub
[go: up one dir, main page]

Skip to content

Commit f7f877b

Browse files
hanss314abranhe
authored andcommitted
Add mergesort
1 parent f3f3484 commit f7f877b

File tree

Expand file tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

sorting/merge_sort.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def merge_sort(l):
2+
if len(l) < 2: return
3+
pivot = len(l)//2
4+
left, right = l[:pivot], l[pivot:]
5+
merge_sort(left)
6+
merge_sort(right)
7+
8+
k = 0
9+
while len(left) > 0 and len(right) > 0:
10+
if left[0] < right[0]:
11+
l[k] = left.pop(0)
12+
else:
13+
l[k] = right.pop(0)
14+
k += 1
15+
16+
rest = left + right
17+
while len(rest) > 0:
18+
l[k] = rest.pop(0)
19+
k += 1
20+

0 commit comments

Comments
 (0)
0