Skip to content

Commit d009cf6

Browse files
committed
Added combsort.cpp
1 parent 07e254f commit d009cf6

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

classical_algorithms/c++/combsort.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
//Comb sort is an improvement over bubble sort, and works by varying the gap when comparing values. It has better average time, but worst case scenario is still the same.
5+
6+
//Algorithm:
7+
int nextGap(int gap){
8+
//Curiosity: this shrink factor for the gap (~=1.3) has been suggested as the ideal one by the original authors of this sorting algorithm, but can actually be changed.
9+
gap = (gap*10)/13;
10+
11+
if(gap < 1){
12+
return 1;
13+
}
14+
return gap;
15+
}
16+
17+
void combSort(int array[], int n){
18+
int gap = n;
19+
//The purpose of the flag is the same as in bubble sort.
20+
bool flag = true;
21+
22+
while (gap != 1 || flag == true){
23+
gap = nextGap(gap);
24+
flag = false;
25+
26+
for (int i = 0; i < (n - gap); i++){
27+
if(array[i] > array[i + gap]){
28+
swap(array[i], array[i + gap]);
29+
flag = true;
30+
}
31+
}
32+
}
33+
}
34+
35+
//Test:
36+
int main(){
37+
int n;
38+
int array[] = {3, 1, 2, 9, -21, 14, 15, 12, 13, 12};
39+
n = sizeof(array) / sizeof(array[0]);
40+
cout << "Elements before comb sort:\n";
41+
for (int i = 0; i < n; i++){
42+
cout << array[i] << " ";
43+
}
44+
cout << "\n";
45+
46+
combSort(array, n);
47+
48+
cout << "Elements after comb sort:\n";
49+
for(int i = 0; i < n; i++){
50+
cout << array[i] << " ";
51+
}
52+
cout << "\n";
53+
}

0 commit comments

Comments
 (0)