combsort Algorithm
Combsort is an efficient in-place comparison-based sorting algorithm that was developed to improve upon the traditional bubble sort algorithm. It was first introduced by Wlodzimierz Dobosiewicz and Artur Borowy in 1980 and later optimized by Stephen Lacey and Richard Box in 1991. The fundamental idea behind combsort is to eliminate "turtles," the small values near the end of the list that hinder the bubble sort's performance. Combsort achieves this by comparing and swapping elements that are a certain distance apart, known as the gap, rather than comparing adjacent elements as in bubble sort. The gap starts with a large value and gradually shrinks over time, eventually reaching 1, making the algorithm behave like bubble sort at the end.
The primary innovation of combsort lies in the gap sequence, which determines the rate at which the gap size decreases. A common choice for the initial gap size is the list length divided by a constant factor, typically 1.3, known as the shrink factor. The gap is then continuously reduced by dividing it by the shrink factor and rounding down to the nearest integer. The algorithm iterates through the list, comparing and swapping elements separated by the current gap size until the gap reaches 1 and no more swaps are needed. This process effectively moves smaller values towards the beginning of the list, allowing the larger values to "bubble" up to the correct positions. Combsort has a time complexity of O(n^2) in the worst case, but its average-case performance is significantly better than bubble sort, with a complexity of O(n log n) for an appropriately chosen shrink factor.
//Kind of better version of Bubble sort.
//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1
//Best case: O(n)
//Worst case: O(n ^ 2)
#include <iostream>
using namespace std;
int a[100005];
int n;
int FindNextGap(int x)
{
x = (x * 10) / 13;
return max(1, x);
}
void CombSort(int a[], int l, int r)
{
//Init gap
int gap = n;
//Initialize swapped as true to make sure that loop runs
bool swapped = true;
//Keep running until gap = 1 or none elements were swapped
while (gap != 1 || swapped)
{
//Find next gap
gap = FindNextGap(gap);
swapped = false;
// Compare all elements with current gap
for (int i = l; i <= r - gap; ++i)
{
if (a[i] > a[i + gap])
{
swap(a[i], a[i + gap]);
swapped = true;
}
}
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> a[i];
CombSort(a, 1, n);
for (int i = 1; i <= n; ++i)
cout << a[i] << ' ';
return 0;
}