You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
925 B
50 lines
925 B
13 years ago
|
# vim:fileencoding=utf-8
|
||
13 years ago
|
import math
|
||
|
|
||
13 years ago
|
|
||
13 years ago
|
def insertion_sort(a):
|
||
13 years ago
|
""" Θ(n^2) """
|
||
13 years ago
|
for j in range(1, len(a)):
|
||
|
key = a[j]
|
||
13 years ago
|
i = j - 1
|
||
13 years ago
|
while i >= 0 and a[i] > key:
|
||
|
a[i + 1] = a[i]
|
||
13 years ago
|
i = i - 1
|
||
13 years ago
|
a[i + 1] = key
|
||
13 years ago
|
|
||
|
|
||
|
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
|
||
|
|