Skip to content

Commit 8a34fde

Browse files
authored
Merge pull request larissalages#263 from mulirow/add-comb-sort
Added combsort.cpp
2 parents 8f3579e + a9ae970 commit 8a34fde

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-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+
}

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ Code | Test
4848
[Insertion Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c++/insertionsort.cpp) | Missing tests
4949
[Bubble Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c++/bubblesort.cpp) | Missing tests
5050
[Merge Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/mergesort.cpp) | Missing tests
51+
[Comb Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/combsort.cpp) | Missing Tests
5152
[Quick Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c++/quicksort.cpp) | Missing tests
5253
[0/1 Knapsack Problem](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/01_knapsack_problem.cpp) | Missing tests
5354
[Kadane's Algorithm](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/Kadane_Algorithm.cpp) | Missing tests

0 commit comments

Comments
 (0)