1. Initial gap
Start by comparing values far apart.
let gap = Math.floor(arr.length / 2)Typorithm · medium
Step 1 of 8 · intro card
Sorting Algorithms
Shell Sort is a gap-based upgrade to Insertion Sort that moves values long distances early.
Insertion Sort is fast when values are already near their final positions.
Shell Sort starts with a large gap so misplaced values can move across the array quickly.
Each gap pass performs insertion-style shifting inside gapped subsequences.
The gap shrinks until it reaches 1, where the final pass behaves like Insertion Sort on a nearly sorted array.
Runtime depends on the gap sequence; this simple halving sequence is easy to learn.
Start with a large gap.
Do insertion-style shifts by that gap.
Shrink the gap after each pass.
Final gap 1 cleans up the array.
In-place and usually faster than plain Insertion Sort.
function shellSort(arr) {
let gap = Math.floor(arr.length / 2);
while (gap > 0) {
for (let i = gap; i < arr.length; i++) {
const current = arr[i];
let j = i;
while (j >= gap && arr[j - gap] > current) {
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = current;
}
gap = Math.floor(gap / 2);
}
return arr;
}Connect each part of the code to the concept before you type.
Start by comparing values far apart.
let gap = Math.floor(arr.length / 2)Repeat passes until the final gap of 1 is completed.
while (gap > 0)Start at gap so j - gap is a valid earlier position.
for (let i = gap; i < arr.length; i++)Save the value before shifting gapped elements.
const current = arr[i]j moves left by gap-sized jumps.
let j = iShift earlier gapped values while they are larger than current.
while (j >= gap && arr[j - gap] > current)Move the larger gapped value right into j.
arr[j] = arr[j - gap]Move to the previous value in the gapped subsequence.
j -= gapSmaller gaps refine the order until gap 1 finishes with insertion-sort behavior.
gap = Math.floor(gap / 2)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
One temporary value and a fixed number of indices. In-place does not mean zero extra memory. The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state