Browse Source

Create merge_sort.py

pull/2/head
Adriano Laureano 6 years ago
committed by GitHub
parent
commit
639d7d30b6
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 27 additions and 0 deletions
  1. +27
    -0
      sorting/merge_sort.py

+ 27
- 0
sorting/merge_sort.py View File

@ -0,0 +1,27 @@
def merge_sort(a):
if len(a) < 2:
return a
l = a[0:len(a)//2]
r = a[len(a)//2:]
return merge(merge_sort(l), merge_sort(r))
def merge(a, b):
out = []
i = 0
j = 0
while i < len(a) or j < len(b):
if i >= len(a):
out.append(b[j])
j += 1
elif j >= len(b):
out.append(a[i])
i += 1
else:
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
return out

Loading…
Cancel
Save