About the Author: Alex, loves programming, reading, cooking and biking
Code
'''
sort.py
'''
import random
import math
import copy
def insertion_sort(array: tuple):
'''
it's like sort a hand of pokers by inserting left to right.
'''
if not isinstance(array, tuple):
raise ParameterTypeError()
a = list(array)
for i in range(len(a)):
j = i
while j > 0 and a[j] < a[j - 1]:
a[j], a[j - 1] = a[j - 1], a[j]
j -= 1
return tuple(a)
def shell_sort(array: tuple):
'''
published by Donald L Shell
basic idea is to swap items that are far apart, reducing swaps
'''
if not isinstance(array, tuple):
raise ParameterTypeError()
a = list(array)
length = len(a)
gaps = (1, 3, 7)
for gap in gaps:
for i in range(gap, length):
j = i
while j >= gap and a[j] < a[j - gap]:
a[j], a[j - gap] = a[j - gap], a[j]
j -= gap
return tuple(a)
def merge_sort(a: list, p: int, r: int):
def merge(a: list, p: int, q: int, r: int):
L = tuple(a[p: q + 1])
R = tuple(a[q + 1: r + 1])
# print('L:', L, 'R:', R, 'p:', p, 'q:', q, 'r:', r, 'a:', a)
i = 0
j = 0
for k in range(p, r + 1):
if i < len(L) and j < len(R):
if L[i] < R[j]:
a[k] = L[i]
i += 1
else:
a[k] = R[j]
j += 1
else:
if i < len(L):
a[k] = L[i]
i += 1
if j < len(R):
a[k] = R[j]
j += 1
if not isinstance(a, list):
raise ParameterTypeError(msg='list expected')
else:
if p < r:
q = math.floor((p + r) / 2)
merge_sort(a, p, q)
merge_sort(a, q + 1, r)
merge(a, p, q, r)
return tuple(a)
def heap_sort(array: tuple):
if not isinstance(array, tuple):
raise ParameterTypeError()
else:
pass
def quick_sort(array: tuple):
if not isinstance(array, tuple):
raise ParameterTypeError()
else:
pass
def bubble_sort(array: tuple):
if not isinstance(array, tuple):
raise ParameterTypeError()
else:
pass
def shuffle(array: tuple):
a = copy.deepcopy(array)
random.shuffle(a)
return tuple(a)
class ParameterTypeError(Exception):
def __init__(self, code=1, msg='tuple expected'):
self.code = code
self.msg = msg
Unit test
'''
test_sort.py
'''
import unittest
import sort
class SortTest(unittest.TestCase):
def setUp(self):
self.limit = 11
array = [i for i in range(1, self.limit)]
self.b = tuple(array)
self.a = sort.shuffle(array)
self.invalid_input = 0
def test_insertion_sort(self):
self.assertRaises(sort.ParameterTypeError, sort.insertion_sort, self.invalid_input)
self.assertEqual(sort.insertion_sort(self.a), self.b, 'sorted')
def test_shell_sort(self):
self.assertRaises(sort.ParameterTypeError, sort.shell_sort, self.invalid_input)
self.assertEqual(sort.shell_sort(self.a), self.b, 'sorted')
def test_merge_sort(self):
self.assertRaises(sort.ParameterTypeError, sort.merge_sort, self.invalid_input, 0, 0)
self.assertEqual(sort.merge_sort(list(self.a), 0, len(self.a)), self.b, 'sorted')
if __name__ == '__main__':
unittest.main()
TO BE CONTINUED