58 lines
1.2 KiB
Python
58 lines
1.2 KiB
Python
from __future__ import print_function
|
|
|
|
import os
|
|
import random
|
|
import timeit
|
|
|
|
|
|
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[:]))
|
|
|
|
for i in range(3):
|
|
random.shuffle(to_sort)
|
|
|
|
for arr, desc in (
|
|
(to_sort_sorted, 'sorted'),
|
|
(to_sort, 'shuffled'),
|
|
(to_sort_reversed, 'reversed')):
|
|
|
|
timing = timeit.timeit(
|
|
lambda: insertion_sort(arr),
|
|
number=10
|
|
)
|
|
print('{} {}: {}'.format(10 ** power, desc, timing))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|