box-o-sand/PracticingAlgorithms/sorting.py
Dan Buch eacc351b17 Add 'PracticingAlgorithms/' from commit '0b723f2ae0a20ab8c90c33db8c1d9d9acd76a86f'
git-subtree-dir: PracticingAlgorithms
git-subtree-mainline: 0a9428093c
git-subtree-split: 0b723f2ae0
2013-01-09 23:58:26 -05:00

50 lines
925 B
Python

# vim:fileencoding=utf-8
import math
def insertion_sort(a):
""" Θ(n^2) """
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0 and a[i] > key:
a[i + 1] = a[i]
i = i - 1
a[i + 1] = key
def merge_sort(m):
n = len(m)
if n <= 1:
return m
middle = math.ceil(n / 2)
left = m[:middle]
right = m[middle:]
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 or len(right) > 0:
if len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
elif len(left) > 0:
result.append(left.pop(0))
elif len(right) > 0:
result.append(right.pop(0))
return result