working through merge sort

This commit is contained in:
Dan Buch 2011-08-15 22:34:46 -04:00
parent 7f555fbe56
commit a7f7b48a77
2 changed files with 79 additions and 0 deletions

View File

@ -1,4 +1,6 @@
# vim:fileencoding=utf-8
import math
def insertion_sort(a):
""" Θ(n^2) """
@ -9,3 +11,39 @@ def insertion_sort(a):
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

View File

@ -45,5 +45,46 @@ class TestInsertionSort(unittest.TestCase):
self.assertEqual(expected, a)
class TestMergeSort(unittest.TestCase):
def test_example(self):
tmpl = [8, 2, 4, 9, 3, 6]
a = tmpl[:]
expected = [2, 3, 4, 6, 8, 9]
actual = sorting.merge_sort(a)
self.assertEqual(expected, actual)
def test_100_example(self):
tmpl = list(range(0, 1000))
a = tmpl[:]
random.shuffle(a)
expected = tmpl[:]
actual = sorting.merge_sort(a)
self.assertEqual(expected, actual)
def test_reversed_100_example(self):
tmpl = list(range(0, 1000))
a = list(reversed(tmpl[:]))
expected = tmpl[:]
actual = sorting.merge_sort(a)
self.assertEqual(expected, actual)
def test_1000_example(self):
tmpl = list(range(0, 1000))
a = tmpl[:]
random.shuffle(a)
expected = tmpl[:]
actual = sorting.merge_sort(a)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()