box-o-sand/intro-to-algorithms/ch02.py

58 lines
1.2 KiB
Python
Raw Normal View History

2012-06-09 18:28:27 +00:00
from __future__ import print_function
import os
import random
import timeit
2012-06-09 18:28:27 +00:00
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
def main():
for power in range(1, 5):
to_sort = list(range(10 ** power))
to_sort_sorted = to_sort[:]
to_sort_reversed = list(reversed(to_sort[:]))
2012-06-09 18:28:27 +00:00
for i in range(3):
random.shuffle(to_sort)
2012-06-09 18:28:27 +00:00
for arr, desc in (
(to_sort_sorted, 'sorted'),
(to_sort, 'shuffled'),
(to_sort_reversed, 'reversed')):
2012-06-09 18:28:27 +00:00
timing = timeit.timeit(
lambda: insertion_sort(arr),
number=10
)
print('{} {}: {}'.format(10 ** power, desc, timing))
2012-06-09 18:28:27 +00:00
if __name__ == '__main__':
main()