Shell sort

Shell Sort is a sorting algorithm based on Insertion sort with time complexity that depends on the gap sequence. unlike insertion sort, it is Unstable, but it is Adaptive.

= Explanation = If an array is H-sorted, it means that starting anywhere, skipping by H, yields a sorted sequence.

Shellsort uses a Gap sequence, a sequence of numbers that start with 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