-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.py
More file actions
52 lines (36 loc) · 1.19 KB
/
shell.py
File metadata and controls
52 lines (36 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from typing import List, Union
def shell_sort(arr: List[Union[int, float]]) -> None:
"""
Sorts a list in ascending order using the shell sort algorithm.
Shell Sort is an optimization over insertion sort that compares elements separated by a gap
and gradually reduces this gap until it's 1, resulting in a final pass of insertion sort.
Args:
arr (List[Union[int, float]]): The list of numbers (integers or floats) to be sorted.
Returns:
None: The function sorts the list in place and does not return a value.
Example:
>>> nums = [1, 34, 21, 1, 5, 3, 54, 9]
>>> shell_sort(nums)
>>> print(nums)
[1, 1, 3, 5, 9, 21, 34, 54]
"""
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2
# Test arrays
array_one = [1, 34, 21, 1, 5, 3, 54, 9]
array_two = [4.5, 3.7, 1.6, 0.4, 23.87]
# Sort arrays
shell_sort(array_two)
shell_sort(array_one)
# Print sorted arrays
print(array_one)
print(array_two)