日本語

COMPARISON SORTS

Comb Sort, visualised

Comb sort is bubble sort with a wide comparison gap that is divided by about 1.3 each pass. It finishes with gap 1 passes until no swaps occur.

Run Comb Sort in the visualizer →

Opens the Sorting Cinema visualizer with 16 elements in English.

How it works

  1. Set the gap to the array length divided by 1.3, rounded down (this app's implementation).
  2. Compare elements one gap apart from the left; swap if the left one is larger.
  3. After each pass, divide the gap by 1.3 and round down.
  4. Once the gap is 1 and a pass makes no swaps, the array is sorted.

Complexity and stability

Best
O(n log n)
Average
— (no claim on this page)
Worst
O(n²)
Extra space
O(1)
Stability
Usually unstable

The worst case is O(n²). On sorted input each gap needs one pass, so about log n gap sizes × n gives O(n log n). This page makes no claim about the average case.

Source of facts: Complexity is derived from the steps of this app's implementation (src/SortingCinema.jsx).

Trace on a small array

The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.

#OperationArray after
1Compare [0]=5 and [3]=1[5, 2, 4, 1, 3]
2Swap [0]=5 and [3]=1[1, 2, 4, 5, 3]
3Compare [1]=2 and [4]=3[1, 2, 4, 5, 3]
4Compare [0]=1 and [2]=4[1, 2, 4, 5, 3]
5Compare [1]=2 and [3]=5[1, 2, 4, 5, 3]
6Compare [2]=4 and [4]=3[1, 2, 4, 5, 3]
7Swap [2]=4 and [4]=3[1, 2, 3, 5, 4]
8Compare [0]=1 and [1]=2[1, 2, 3, 5, 4]

…and so on. In this trace, 16 compare / swap / write operations in total produce [1, 2, 3, 4, 5].

Suitable inputs and caveats

  • Wide gaps move small values near the right end leftwards early — the weak spot of bubble sort.
  • Performance depends on the shrink factor; this app uses 1.3.
  • It swaps distant elements, so it is usually unstable.

FAQ

How does comb sort differ from bubble sort?

Bubble sort always compares neighbours. Comb sort starts with a wide gap, shrinks it, and finishes with neighbour comparisons.

What does the shrink factor 1.3 mean?

Each pass divides the gap by 1.3 and rounds down — this app's setting. A different factor changes the number of passes.