|
| 1 | +""" |
| 2 | +This is a pure python implementation of the shell sort algorithm |
| 3 | +
|
| 4 | +For doctests run following command: |
| 5 | +python -m doctest -v shell_sort.py |
| 6 | +or |
| 7 | +python3 -m doctest -v shell_sort.py |
| 8 | +
|
| 9 | +For manual testing run: |
| 10 | +python shell_sort.py |
| 11 | +""" |
| 12 | +from __future__ import print_function |
| 13 | + |
| 14 | + |
| 15 | +def shell_sort(collection): |
| 16 | + """Pure implementation of shell sort algorithm in Python |
| 17 | + :param collection: Some mutable ordered collection with heterogeneous |
| 18 | + comparable items inside |
| 19 | + :return: the same collection ordered by ascending |
| 20 | + |
| 21 | + >>> shell_sort([0, 5, 3, 2, 2)] |
| 22 | + [0, 2, 2, 3, 5] |
| 23 | +
|
| 24 | + >>> shell_sort([]) |
| 25 | + [] |
| 26 | + |
| 27 | + >>> shell_sort([-2, -5, -45]) |
| 28 | + [-45, -5, -2] |
| 29 | + """ |
| 30 | + # Marcin Ciura's gap sequence |
| 31 | + gaps = [701, 301, 132, 57, 23, 10, 4, 1] |
| 32 | + |
| 33 | + for gap in gaps: |
| 34 | + i = gap |
| 35 | + while i < len(collection): |
| 36 | + temp = collection[i] |
| 37 | + j = i |
| 38 | + while j >= gap and collection[j-gap] > temp: |
| 39 | + collection[j] = collection[j - gap] |
| 40 | + j -= gap |
| 41 | + collection[j] = temp |
| 42 | + i += 1 |
| 43 | + |
| 44 | + |
| 45 | + return collection |
| 46 | + |
| 47 | +if __name__ == '__main__': |
| 48 | + import sys |
| 49 | + # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin |
| 50 | + # otherwise 2.x's input builtin function is too "smart" |
| 51 | + if sys.version_info.major < 3: |
| 52 | + input_function = raw_input |
| 53 | + else: |
| 54 | + input_function = input |
| 55 | + |
| 56 | + user_input = input_function('Enter numbers separated by a comma:\n') |
| 57 | + unsorted = [int(item) for item in user_input.split(',')] |
| 58 | + print(shell_sort(unsorted)) |
0 commit comments