File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -65,6 +65,37 @@ def insertion_sort(arr: List[float]) -> List[float]:
65
65
return arr
66
66
67
67
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
+
68
99
# Insertion sort for any subsequence. Helper for other
69
100
# sorting algorithms like mergesort and quicksort.
70
101
def _subsequence_insertion_sort (arr : List [float ], lo : int , hi : int ) -> None :
You can’t perform that action at this time.
0 commit comments