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.
58 lines
1.3 KiB
58 lines
1.3 KiB
13 years ago
|
from __future__ import print_function
|
||
|
|
||
|
import os
|
||
|
import random
|
||
|
import unittest
|
||
|
|
||
|
|
||
|
DEBUG = os.environ.get('DEBUG') == '1'
|
||
|
|
||
|
|
||
|
def debug(msg):
|
||
|
if DEBUG:
|
||
|
print(msg)
|
||
|
|
||
|
|
||
|
def insertion_sort(arr):
|
||
|
debug('BEGIN')
|
||
|
for j in range(1, len(arr)):
|
||
|
key = arr[j]
|
||
|
i = j - 1
|
||
|
debug('FOR:\tj={}, key={}, i={}'.format(j, key, i))
|
||
|
|
||
|
while i > -1 and arr[i] > key:
|
||
|
arr[i + 1] = arr[i]
|
||
|
debug('WHILE:\tset: arr[{}] = {}'.format(i + 1, arr[i]))
|
||
|
i = i - 1
|
||
|
|
||
|
arr[i + 1] = key
|
||
|
debug('FOR:\tset: arr[{}] = {}'.format(i + 1, key))
|
||
|
|
||
|
debug('END')
|
||
|
return arr
|
||
|
|
||
|
|
||
|
class TestStuff(unittest.TestCase):
|
||
|
|
||
|
def test_insertion_sort_small(self):
|
||
|
self.assertEqual(
|
||
|
[1, 2, 3, 4, 5, 6],
|
||
|
insertion_sort([5, 2, 4, 6, 1, 3])
|
||
|
)
|
||
|
|
||
|
def test_insertion_sort_large(self):
|
||
|
inlist = range(1000)
|
||
|
listcopy = inlist[:]
|
||
|
random.shuffle(inlist)
|
||
|
random.shuffle(inlist)
|
||
|
self.assertEqual(listcopy, insertion_sort(inlist))
|
||
|
|
||
|
def test_insertion_sort_large_reversed(self):
|
||
|
inlist = range(1000)
|
||
|
listcopy = inlist[:]
|
||
|
self.assertEqual(listcopy, insertion_sort(list(reversed(inlist))))
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
unittest.main()
|