2012-06-09 18:28:27 +00:00
|
|
|
from __future__ import print_function
|
|
|
|
|
|
|
|
import os
|
|
|
|
import random
|
2012-06-10 00:53:29 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
|
2012-06-10 00:53:29 +00:00
|
|
|
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
|
|
|
|
2012-06-10 00:53:29 +00:00
|
|
|
for i in range(3):
|
|
|
|
random.shuffle(to_sort)
|
2012-06-09 18:28:27 +00:00
|
|
|
|
2012-06-10 00:53:29 +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
|
|
|
|
2012-06-10 00:53:29 +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__':
|
2012-06-10 00:53:29 +00:00
|
|
|
main()
|