Skip to content

Commit e902adf

Browse files
committed
Add a shellsort implementation
1 parent fc5cbde commit e902adf

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

sorting_algorithms.py

+31
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,37 @@ def insertion_sort(arr: List[float]) -> List[float]:
6565
return arr
6666

6767

68+
def shellsort(arr: List[float]) -> List[float]:
69+
gap_size = 1
70+
71+
# Using Knuth's increment sequence due to ease of generation.
72+
# https://oeis.org/A003462
73+
while gap_size < len(arr) // 3:
74+
gap_size = 3 * gap_size + 1
75+
76+
# The final gap size of 1 will perform an insertion sort and guarantee
77+
# that the array is sorted.
78+
while gap_size >= 1:
79+
80+
# h-sort the array by the gap size.
81+
for i, curr_num in enumerate(arr):
82+
prev_elements_ptr = i - gap_size
83+
84+
# Compare the current element with all previously considered
85+
# elements in the current gap sequence, moving the considered
86+
# element to the right by the gap size if the current is smaller.
87+
while prev_elements_ptr >= 0 and curr_num < arr[prev_elements_ptr]:
88+
arr[prev_elements_ptr + gap_size] = arr[prev_elements_ptr]
89+
prev_elements_ptr -= gap_size
90+
91+
# Now set the current element to its h-sorted location.
92+
arr[prev_elements_ptr + gap_size] = curr_num
93+
94+
gap_size //= 3
95+
96+
return arr
97+
98+
6899
# Insertion sort for any subsequence. Helper for other
69100
# sorting algorithms like mergesort and quicksort.
70101
def _subsequence_insertion_sort(arr: List[float], lo: int, hi: int) -> None:

0 commit comments

Comments
 (0)