1
1
"""
2
- This function implements the shell sort algorithm.
2
+ This function implements the shell sort algorithm
3
+ which is slightly faster than its pure implementation.
3
4
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 .
5
+ This shell sort is implemented using a gap, which
6
+ shrinks by a certain factor each iteration. In this
7
+ implementation, the gap is initially set to the
8
+ length of the collection. The gap is then reduced by
9
+ a certain factor (1.3) each iteration .
9
10
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.
11
+ For each iteration, the algorithm compares elements
12
+ that are a certain number of positions apart
13
+ (determined by the gap). If the element at the higher
14
+ position is greater than the element at the lower
15
+ position, the two elements are swapped. The process
16
+ is repeated until the gap is equal to 1.
18
17
18
+ The reason this is more efficient is that it reduces
19
+ the number of comparisons that need to be made. By
20
+ using a smaller gap, the list is sorted more quickly.
19
21
"""
20
22
23
+
21
24
def shell_sort (collection : list ) -> list :
22
25
"""Implementation of shell sort algorithm in Python
23
26
:param collection: Some mutable ordered collection with heterogeneous
24
27
comparable items inside
25
28
:return: the same collection ordered by ascending
26
-
29
+
27
30
>>> shell_sort([3, 2, 1])
28
31
[1, 2, 3]
29
32
>>> shell_sort([])
@@ -59,8 +62,5 @@ def shell_sort(collection: list) -> list:
59
62
60
63
if __name__ == "__main__" :
61
64
import doctest
62
- doctest .testmod ()
63
65
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 ))
66
+ doctest .testmod ()
0 commit comments