Typorithm · medium

Comb Sort

▷ Interactive algorithm labcomb-sortsortinggapbubble-sortquadratic-time
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Comb Sort

0%

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.

Preparing algorithm lab…
01

Start with gap = arr.length.

02

Shrink gap by about 1.3.

03

Compare i with i + gap.

04

Finish when gap is 1 and no swaps occur.

05

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Initial gap

Comb Sort starts with a wide gap instead of adjacent pairs.

let gap = arr.length

2. Swap flag

The loop continues until gap is 1 and no swaps happen.

let swapped = true

3. Loop condition

Keep going while gaps remain or the last adjacent pass still swapped.

while (gap > 1 || swapped)

4. Shrink gap

The gap shrinks by about 1.3 but never below 1.

gap = Math.max(1, Math.floor(gap / 1.3))

5. Gapped scan

Only compare pairs where i + gap is still in bounds.

for (let i = 0; i + gap < arr.length; i++)

6. Gapped comparison

Compare values separated by the current gap.

arr[i] > arr[i + gap]

7. Gapped swap

Swap distant out-of-order values.

[arr[i], arr[i + gap]] = [arr[i + gap], arr[i]]

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Comb Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn