-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell_sort.py
More file actions
50 lines (34 loc) · 1.27 KB
/
Copy pathshell_sort.py
File metadata and controls
50 lines (34 loc) · 1.27 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
"""Shell Sort - insertion sort applied over progressively smaller gaps.
Uses Shell's original halving gap sequence (n/2, n/4, ... 1). It is the easiest
sequence to follow, but it is also the reason this implementation has an O(n^2)
worst case; sequences such as Ciura's or Sedgewick's do better at the cost of
readability.
"""
def shellSort(arr: list) -> None:
"""Sort `arr` in place using the halving gap sequence."""
n = len(arr)
gap = n // 2
while gap > 0:
# Perform a "gapped" insertion sort for this gap size
for i in range(gap, n):
# Current element to be placed correctly
temp = arr[i]
j = i
# Shift earlier elements that are greater than temp
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
# Place temp in its correct position
arr[j] = temp
# Reduce the gap
gap //= 2
def printArray(arr: list) -> None:
"""Print the array on a single space-separated line."""
print(" ".join(map(str, arr)))
if __name__ == "__main__":
arr = [12, 34, 54, 2, 3]
print("Original array: ", end="")
printArray(arr)
shellSort(arr)
print("Sorted array: ", end="")
printArray(arr)