1. Initial gap
Comb Sort starts with a wide gap instead of adjacent pairs.
let gap = arr.lengthTyporithm · medium
Step 1 of 8 · intro card
Sorting Algorithms
Comb Sort improves Bubble Sort by comparing values at a shrinking gap before finishing with adjacent swaps.
Bubble Sort only swaps adjacent values, so distant small values move slowly.
Comb Sort starts with a large gap so badly misplaced values can jump farther.
The gap shrinks by a factor until it reaches 1.
When gap is 1, the algorithm behaves like Bubble Sort with an early-exit flag.
It is usually faster than Bubble Sort but still has quadratic worst-case behavior.
Start with gap = arr.length.
Shrink gap by about 1.3.
Compare i with i + gap.
Finish when gap is 1 and no swaps occur.
Not stable because distant swaps can cross equal values.
function combSort(arr) {
let gap = arr.length;
let swapped = true;
while (gap > 1 || swapped) {
gap = Math.max(1, Math.floor(gap / 1.3));
swapped = false;
for (let i = 0; i + gap < arr.length; i++) {
if (arr[i] > arr[i + gap]) {
[arr[i], arr[i + gap]] = [arr[i + gap], arr[i]];
swapped = true;
}
}
}
return arr;
}Connect each part of the code to the concept before you type.
Comb Sort starts with a wide gap instead of adjacent pairs.
let gap = arr.lengthThe loop continues until gap is 1 and no swaps happen.
let swapped = trueKeep going while gaps remain or the last adjacent pass still swapped.
while (gap > 1 || swapped)The gap shrinks by about 1.3 but never below 1.
gap = Math.max(1, Math.floor(gap / 1.3))Only compare pairs where i + gap is still in bounds.
for (let i = 0; i + gap < arr.length; i++)Compare values separated by the current gap.
arr[i] > arr[i + gap]Swap distant out-of-order values.
[arr[i], arr[i + gap]] = [arr[i + gap], arr[i]]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