Shell sort speeds up insertion sort by letting values jump far in one move. It first sorts elements that are far apart, then closer together, and finishes with an ordinary insertion sort on data that is already nearly in order.
Insertion sort is slow on random data because each value moves only one place at a time. A small value near the end has to be shifted past almost everything. Shell sort fixes this by first comparing values that are a distance h apart, called the gap (or interval).
The gaps come from a gap sequence. This page uses Knuth's sequence: 1, 4, 13, 40, 121, …, where each gap is 3 times the previous one plus 1. The sort starts with the largest gap below n / 3 and works down to 1.
Sorting {35, 33, 42, 10, 14, 19, 27, 44, 26, 31}. With 10 values, Knuth's sequence gives the gaps 4 and 1. In the gap 4 rows, each color is one sublist.
The array in main() changes to match what you sort.
Shell sort's running time depends on the gap sequence, and there is no simple formula for the average case. What is known:
It sorts in place with O(1) extra memory, just like insertion sort. It is not stable: a long jump can carry a value past an equal value in another sublist. Try the Equal values preset.
The table compares Shell sort with plain insertion sort on the same arrays. Look at how the gap passes cut down the shifts.
Start at 1 and keep going while the gap is below 100 / 3 = 33: 1 → 4 → 13 → 40. 40 is not below 33, so the sort uses 40, 13, 4 and then 1.
The bigger gaps have already moved every value close to its final place. Insertion sort is adaptive: on nearly sorted data each value shifts only a few places, so the last pass costs little more than n comparisons.
Each gap pass is a stable insertion sort within one sublist, but two equal values can sit in different sublists. In 5a, 5b, 7, 8, 2, 9, the gap 4 pass swaps 5a with 2, sending 5a to index 4, past 5b at index 1. The final order is 5b before 5a.
The array would only be h-sorted for the smallest h used, not fully sorted. The final gap of 1 is what guarantees a sorted result; the larger gaps only make that last pass faster.