Browse Source

Merge pull request #2 from sl4ureano/master

Add merge_sort and radix_sort
pull/6/head
Jeffery Russell 6 years ago
committed by GitHub
parent
commit
913d745e2a
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions
  1. +27
    -0
      sorting/merge_sort.py
  2. +14
    -0
      sorting/radix_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

+ 14
- 0
sorting/radix_sort.py View File

@ -0,0 +1,14 @@
def radix_sort(lista):
max_len = max([len(numero) for numero in lista])
padded = list([str(num).rjust(max_len, "0") for num in lista])
for pos in reversed(range(max_len)):
buckets = [list() for x in range(0, 10)]
for num in padded:
bucket = int(num[pos])
buckets[bucket] += [num]
padded = sum(buckets, [])
return padded
if __name__ == "__main__":
print(radix_sort(["13", "105", "10", "150"]))

Loading…
Cancel
Save