Lesson 47 · Core algorithms

Shell Sort: Gap Sequences and Cost

Insertion-sort the values that are a gap apart, shrink the gap, and finish with a gap of 1 on an array that is already nearly sorted.

Shell Sort: Gap Sequences and Cost concept diagramA visual explanation of the layout and operations shown in this lesson.insertion sort over a gap, then a smaller gap, then gap 162083118253374175956867gap 4 compares index 0 with index 4a value far from home moves 4 slots in one step, not 4 separate shiftsthe final gap is always 1, so the last pass is ordinary insertion sort
1

How the Shell Sort Algorithm Works

  1. Choose a gap sequence ending in 1, such as n/2, n/4, …, 1
  2. For the current gap, insertion-sort every chain of values that gap apart
  3. Move to the next, smaller gap
  4. Finish with gap 1 on the nearly sorted array

Shell sort, published by Donald Shell in 1959, is insertion sort with a twist: instead of comparing neighbours, it first compares values that are gap positions apart. Values that far apart form separate chains, and each chain is insertion-sorted on its own. Then the gap shrinks and the process repeats.

After a pass with gap h the array is h-sorted: every value is no larger than the one h places to its right. The final pass always uses gap 1, which is plain insertion sort, so the result is always fully sorted.

  • Same compare-and-shift as insertion sort, just over a longer stride
  • Early passes work on short chains, so they are cheap
  • Later passes start from nearly sorted data, so they are cheap too
2

Worked Example: [8, 5, 3, 9, 1, 6]

With n = 6, halving gives gaps 3 and 1. Gap 3 makes three chains: positions {0, 3} hold 8 and 9, {1, 4} hold 5 and 1, {2, 5} hold 3 and 6. Only the middle chain is out of order, so 1 moves from index 4 to index 1 in one step: [8, 1, 3, 9, 5, 6].

Gap 1 is ordinary insertion sort on that array: 1 moves to the front, 3 to index 1, 9 stays, 5 shifts past 9 and 8, and 6 shifts past 9 and 8. The result is [1, 3, 5, 6, 8, 9] after 7 moves in total, where insertion sort on the original would make 9 shifts.

  • Gap 3: one move, 8 and 9 and 3 and 6 already in order
  • Gap 1: six shifts on the nearly sorted array
  • 7 moves against 9 for insertion sort
3

Why Big Gaps Make It Faster

An inversion is a pair of values in the wrong order. Insertion sort shifts one value one place at a time, which fixes exactly one inversion per shift. So its cost equals the number of inversions, up to n(n − 1)/2 for a reversed array.

A move across a gap jumps a value past everything in between and can fix many inversions at once. In the example, moving 1 three places cut the count from 9 to 6. On eight values in reverse order (28 inversions), gaps 4, 2 and 1 need only 4 + 4 + 4 = 12 moves against insertion sort's 28.

The large gaps do the long-distance work; the small gaps tidy up. By the time the gap is 1, few inversions are left, and insertion sort is fast on nearly sorted data.

  • Insertion sort: one inversion fixed per shift
  • A gapped move can fix several
  • Reversed 8 values: 12 moves vs 28
Key reference

Terms, operations, and practical uses

Core mechanics

  • GapThe stride between compared elements; each pass runs insertion sort over every gap-spaced subsequence.
  • h-sortedAn array where every element is in order relative to the one h positions away.
  • Final passAlways gap 1 — a plain insertion sort, but nearly free because earlier passes removed most inversions.

Gap sequences

  • Shell's originalRepeated halving of n. Simple, but O(n²) worst case because even gaps never compare odd with even positions.
  • Knuth1, 4, 13, 40… (3k+1). O(n^1.5) worst case and easy to generate on the fly.
  • CiuraThe empirically tuned 1, 4, 10, 23, 57, 132, 301, 701 — fastest known in practice, with no proven bound.

In practice

  • No recursionRuns in O(1) space with no call stack, which suits embedded and kernel code.
  • uClibc qsortShips shell sort rather than quicksort to avoid recursion depth in constrained environments.
  • Not stableLong-range gapped exchanges jump elements over equal keys.
Implementation

Code in Python, C++ and Java

def shell_sort(values):
    gap = len(values) // 2
    while gap > 0:
        # A gapped insertion sort: same shifting, but g positions at a time.
        for i in range(gap, len(values)):
            current = values[i]
            j = i
            while j >= gap and values[j - gap] > current:
                values[j] = values[j - gap]
                j -= gap
            values[j] = current
        gap //= 2
    return values


print(shell_sort([8, 5, 3, 9, 1, 6]))
#include <iostream>
#include <vector>
using namespace std;

vector<int> shellSort(vector<int> values) {
    int n = (int)values.size();
    for (int gap = n / 2; gap > 0; gap /= 2) {
        // A gapped insertion sort: same shifting, but gap positions at a time.
        for (int i = gap; i < n; i++) {
            int current = values[i];
            int j = i;
            while (j >= gap && values[j - gap] > current) {
                values[j] = values[j - gap];
                j -= gap;
            }
            values[j] = current;
        }
    }
    return values;
}

int main() {
    vector<int> sorted = shellSort({8, 5, 3, 9, 1, 6});
    cout << "[";
    for (size_t i = 0; i < sorted.size(); i++) cout << (i ? ", " : "") << sorted[i];
    cout << "]" << endl;
    return 0;
}
import java.util.Arrays;

public class Main {
    static int[] shellSort(int[] values) {
        int n = values.length;
        for (int gap = n / 2; gap > 0; gap /= 2) {
            // A gapped insertion sort: same shifting, gap positions at a time.
            for (int i = gap; i < n; i++) {
                int current = values[i];
                int j = i;
                while (j >= gap && values[j - gap] > current) {
                    values[j] = values[j - gap];
                    j -= gap;
                }
                values[j] = current;
            }
        }
        return values;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(shellSort(new int[]{8, 5, 3, 9, 1, 6})));
    }
}
Watch it run

Step through it

Running on [8, 5, 3, 9, 1, 6]

input: [8, 5, 3, 9, 1, 6]805132931465inversions left: 9gaps: 6 / 2 = 3, then 3 / 2 = 1
Step 1

Six values, nine inversions

An inversion is a pair in the wrong order, like 8 before 5. This array has 9. Insertion sort removes exactly one inversion per shift, so it would need 9 shifts. Shell sort tries to remove several per move by comparing values far apart first.

Output
1 / 11
4

Shell Sort Time Complexity and Gap Sequences

Shell sort has no single running time; it depends on the gap sequence. Shell's halving sequence is O(n²) in the worst case. The reason is that with gaps n/2, n/4, … (when n is a power of 2) every gap except 1 is even, so values at even positions are never compared with values at odd ones. If small values sit at even positions and large ones at odd positions, every pass before the last does nothing.

Sequences whose gaps are not all multiples of each other avoid this. Knuth's 1, 4, 13, 40, … (each 3h + 1) gives O(n^1.5), Sedgewick's gives O(n^4/3), and Pratt's gaps of the form 2^p·3^q give O(n log² n), though with many passes. Ciura's 1, 4, 10, 23, 57, 132, 301, 701 was found by experiment and is among the fastest in practice, with no proven bound.

On already sorted input each pass only compares, so the best case is about O(n log n) with halving. Extra space is O(1): the sort is in place and needs no recursion.

Common gap sequences
SequenceGapsWorst case
Shell (1959)n/2, n/4, …, 1O(n²)
Hibbard1, 3, 7, 15, … (2^k − 1)O(n^1.5)
Knuth1, 4, 13, 40, … (3h + 1)O(n^1.5)
Sedgewick (1986)1, 8, 23, 77, 281, …O(n^4/3)
Ciura (2001)1, 4, 10, 23, 57, 132, 301, 701Not proven
  • Worst case set by the gaps, not the loop
  • Avoid gaps that all share a factor
  • Space O(1) whichever sequence is used
5

Stability and Where Shell Sort Is Used

Shell sort is not stable. A long jump can carry a value past an equal one. In [1, 2, 1a, 1b] with gap 2, 1b trades places with 2 and lands at index 1, ahead of 1a, and no later pass puts them back.

Its strengths are small code, no extra memory and no recursion, which suits embedded systems and small libraries. uClibc's qsort is a shell sort, and bzip2 uses one inside its block sorter. For large general-purpose sorts, quicksort, merge sort or a hybrid of them is usually faster.

  • Not stable: long jumps skip over equal values
  • In place with no recursion
  • Used where memory and code size matter more than peak speed