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.

Algorithm
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
Sort the array  using gaps  :

3-sort the array using gapped Insertion sort:

[4 0  5  6  1  9  2  7  3  8]   gap = [3  1] ↑ [2 0  5  4  1  9  6  7  3  8]  ↑        ↑        ↑        ↑ [2  0  5  4  1  9  6  7  3  8]     ↑        ↑        ↑ [2  0  3  4  1  5  6  7  9  8]        ↑        ↑        ↑

Gapped Insertion sort of size 1 is the same as Insertion sorting the entire array: [2 0  3  4  1  5  6  7  9  8]   gap = [3  1] ↑ [0 1  2  3  4  5  6  7  8  9]  ↑  ↑  ↑  ↑  ↑  ↑  ↑  ↑  ↑  ↑

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