1
+ """
2
+ This function implements the shell sort algorithm.
3
+
4
+ Shell sort is a sorting algorithm that works by first sorting
5
+ elements that are far apart from each other, and then sorting
6
+ elements that are closer together. This reduces the amount of
7
+ swapping that needs to be done, and makes the algorithm more
8
+ efficient.
9
+
10
+ The algorithm works by first choosing a 'gap' value. This value
11
+ determines how far apart the elements will be that are sorted
12
+ first. The gap is then decreased, and the elements are sorted
13
+ again. This process is repeated until the gap is 1, at which
14
+ point the elements are sorted using insertion sort.
15
+
16
+ Shell sort is an efficient algorithm that is easy to implement.
17
+ It is a good choice for sorting large arrays of data.
18
+
19
+ """
20
+
21
+ def shell_sort (collection ):
22
+ """Implementation of shell sort algorithm in Python
23
+ :param collection: Some mutable ordered collection with heterogeneous
24
+ comparable items inside
25
+ :return: the same collection ordered by ascending
26
+
27
+ >>> shell_sort([3, 2, 1])
28
+ [1, 2, 3]
29
+ >>> shell_sort([])
30
+ []
31
+ >>> shell_sort([1])
32
+ [1]
33
+ """
34
+
35
+ # Choose an initial gap value
36
+ gap = len (collection )
37
+
38
+ # Set the gap value to be decreased by a factor of 1.3
39
+ # after each iteration
40
+ shrink = 1.3
41
+
42
+ # Continue sorting until the gap is 1
43
+ while gap > 1 :
44
+
45
+ # Decrease the gap value
46
+ gap = int (gap / shrink )
47
+
48
+ # Sort the elements using insertion sort
49
+ for i in range (gap , len (collection )):
50
+ temp = collection [i ]
51
+ j = i
52
+ while j >= gap and collection [j - gap ] > temp :
53
+ collection [j ] = collection [j - gap ]
54
+ j -= gap
55
+ collection [j ] = temp
56
+
57
+ return collection
58
+
59
+
60
+ if __name__ == "__main__" :
61
+ import doctest
62
+ doctest .testmod ()
63
+
64
+ user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
65
+ collection = [int (item ) for item in user_input .split ("," )]
66
+ print (shell_sort (collection ))
0 commit comments