# C++ Program for the Comb Sort?

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Comb sort is similar to bubble sort and cocktail sort. Comb sort doesn’t start off looking at adjacent elements but instead looks at elements a certain number of indexes apart, this is called the gap. The gap is defined as [n/c] where n is the number of elements and c is the shrink factor. After each iteration, this number is against divided by c and floored until eventually, the algorithm is looking at adjacent elements.

Input:53421
Output:12345

## Explanation

Comb sort compare two elements with a gap which is defined as [n/c] where n is the number of elements and c is the shrink factor i.e. 1.3. After each iteration, this number is against divided by c and floored until eventually, the algorithm is looking at adjacent elements.

## Example

#include <iostream>
using namespace std;
void combsort(int a[], int n) {
int i, j, gap, swapped = 1;
double temp;
gap = n;
while (gap > 1 || swapped == 1) {
gap = gap * 10 / 1.3;
if (gap == 9 || gap == 10) {
gap = 11;
}
if (gap < 1) {
gap = 1;
}
swapped = 0;
for (i = 0, j = gap; j < n; i++, j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
swapped = 1;
}
}
}
}
int main () {
int n, i;
int arr[] = { 5, 3, 4, 2, 1 };
n=5;
combsort(arr, n);
for(i = 0;i < n;i++) {
cout<<arr[i]<<"\t";
}
return 0;
}
Updated on 19-Aug-2019 11:27:25

Advertisements