messing around with insertion sort
This commit is contained in:
parent
db1a5a113b
commit
88658c2a5d
57
intro-to-algorithms/ch01.py
Normal file
57
intro-to-algorithms/ch01.py
Normal file
@ -0,0 +1,57 @@
|
||||
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()
|
Loading…
Reference in New Issue
Block a user