TheAlgorithms-Python
40 строк · 1.1 Кб
1"""
2https://en.wikipedia.org/wiki/Shellsort#Pseudocode
3"""
4
5
6def shell_sort(collection: list[int]) -> list[int]:
7"""Pure implementation of shell sort algorithm in Python
8:param collection: Some mutable ordered collection with heterogeneous
9comparable items inside
10:return: the same collection ordered by ascending
11
12>>> shell_sort([0, 5, 3, 2, 2])
13[0, 2, 2, 3, 5]
14>>> shell_sort([])
15[]
16>>> shell_sort([-2, -5, -45])
17[-45, -5, -2]
18"""
19# Marcin Ciura's gap sequence
20
21gaps = [701, 301, 132, 57, 23, 10, 4, 1]
22for gap in gaps:
23for i in range(gap, len(collection)):
24insert_value = collection[i]
25j = i
26while j >= gap and collection[j - gap] > insert_value:
27collection[j] = collection[j - gap]
28j -= gap
29if j != i:
30collection[j] = insert_value
31return collection
32
33
34if __name__ == "__main__":
35from doctest import testmod
36
37testmod()
38user_input = input("Enter numbers separated by a comma:\n").strip()
39unsorted = [int(item) for item in user_input.split(",")]
40print(shell_sort(unsorted))
41