Shellsort

Shellsort is a sorting algorithm based on Insertion sort with time complexity that depends on the gap sequence, but universally requiring $$O(1)$$ memory. Unlike insertion sort, it is unstable, but it is adaptive.

= Explanation = If an array is H-sorted, it means that if you start anywhere in the list, skipping by H will yield a sorted sequence.

Shellsort uses a gap sequence, a sequence of numbers that start with 1.

The original gap sequence starts at a gap of $$n/2$$, and then divides by 2 until the gap reaches 1.

It H-sorts according to the gap sequence: for example if the gap sequence was 1, 4, 13, 40, 121, it would 121-sort, then 40-sort, 13-sort, 4-sort, and finally 1-sort, which is equivalent to Insertion Sort.

= Example = Take the array 12, 9, 3, 11, 4, 1, 2, 7, 6, 13, 14, 5, 8, 15, 16, 10.

first, 13-sort it.

12, 9, 3, 11, 4, 1, 2, 7, 6, 13, 14, 5, 8, 15, 16, 10

next, 4-sort it.

6, 1, 2, 5, 14, 9, 3, 7, 12, 13, 14, 11, 8, 15, 16, 10

Finally, 1-sort it.

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16

= Pseudocode = array gaps = [1,4,13,40,121,364,1093,3280] #(3^n-1)/2 gaps procedure shell_sort(array arr) do int k = 0 while gaps[i] < length(arr) do k ++ end while while k >= 0 do for offset = 0 to gaps[k] do for i = offset, i < length(arr), i += gaps[k] do elem temp = arr[i] for j = i, j >= gaps[k] and arr[j - gaps[k]] > temp, j -= gaps[k] arr[j] = arr[j - gaps[k]] end for arr[j] = temp end for end for k -- end while end

= Gap sequences =