AlgoLab

O(n²)·O(1) space·not stable
645559896316373459948511843281951114277

Starting comb sort on an array of 20 items.

Starting comb sort on an array of 20 items.
  1. 1set the gap to the length of the array
  2. 2shrink the gap by dividing it by 1.3, with a minimum of one
  3. 3compare each pair of values that many positions apart, from the start to the end
  4. 4if the left value is greater than the right value, swap them
  5. 5if the gap is one and that pass made no swaps, the array is sorted
  6. 6the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n log n)
AverageO(n²)
WorstO(n²)
Extra spaceO(1)
StableNo
n² at n=20 predicts 400; this run took 0.

Comb sort

Comb sort is bubble sort with the comparison gap widened: instead of only ever comparing neighbours, it starts by comparing values a whole array-length apart and shrinks that gap by a factor of roughly 1.3 every pass, finishing with a gap of one, which is an ordinary bubble sort pass.

When it is the right choice

It is worth knowing as the natural next step from bubble sort once the turtle problem is understood, and it is a fair general-purpose exchange sort for a bit more implementation effort than bubble sort. It is not a serious competitor to shell sort, insertion sort, or any O(n log n) sort, and its final full pass at a gap of one still costs an ordinary O(n²) worst case just like bubble sort.

How it works

Worth noticing

Cost

Best
O(n log n)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stable
No

Worth comparing

All algorithms