Skip to content

Commit b423bc4

Browse files
authored
Create combsort.cpp
1 parent 8723339 commit b423bc4

File tree

1 file changed

+118
-0
lines changed

1 file changed

+118
-0
lines changed

Algorithms/Sorting/combsort.cpp

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
// C++ implementation of Comb Sort
2+
3+
//facebook,netflix
4+
5+
#include<bits/stdc++.h>
6+
using namespace std;
7+
8+
// To find gap between elements
9+
int getNextGap(int gap)
10+
{
11+
// Shrink gap by Shrink factor
12+
gap = (gap*10)/13;
13+
14+
if (gap < 1)
15+
return 1;
16+
return gap;
17+
}
18+
19+
// Function to sort a[0..n-1] using Comb Sort
20+
void combSort(int a[], int n)
21+
{
22+
// Initialize gap
23+
int gap = n;
24+
25+
// Initialize swapped as true to make sure that loop runs
26+
bool swapped = true;
27+
28+
// Keep running while gap is more than 1 and last iteration caused a swap
29+
while (gap != 1 || swapped == true)
30+
{
31+
// Find next gap
32+
gap = getNextGap(gap);
33+
34+
// Initialize swapped as false so that we can check if swap happened or not
35+
swapped = false;
36+
37+
// Compare all elements with current gap
38+
for (int i=0; i<n-gap; i++)
39+
{
40+
if (a[i] > a[i+gap])
41+
{
42+
swap(a[i], a[i+gap]);
43+
swapped = true;
44+
}
45+
}
46+
}
47+
}
48+
49+
int main()
50+
{
51+
int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
52+
int n = sizeof(a)/sizeof(a[0]);
53+
54+
combSort(a, n);
55+
56+
printf("Sorted array: \n");
57+
for (int i=0; i<n; i++)
58+
printf("%d ", a[i]);
59+
60+
return 0;
61+
}// C++ implementation of Comb Sort
62+
#include<bits/stdc++.h>
63+
using namespace std;
64+
65+
// To find gap between elements
66+
int getNextGap(int gap)
67+
{
68+
// Shrink gap by Shrink factor
69+
gap = (gap*10)/13;
70+
71+
if (gap < 1)
72+
return 1;
73+
return gap;
74+
}
75+
76+
// Function to sort a[0..n-1] using Comb Sort
77+
void combSort(int a[], int n)
78+
{
79+
// Initialize gap
80+
int gap = n;
81+
82+
// Initialize swapped as true to make sure that loop runs
83+
bool swapped = true;
84+
85+
// Keep running while gap is more than 1 and last iteration caused a swap
86+
while (gap != 1 || swapped == true)
87+
{
88+
// Find next gap
89+
gap = getNextGap(gap);
90+
91+
// Initialize swapped as false so that we can check if swap happened or not
92+
swapped = false;
93+
94+
// Compare all elements with current gap
95+
for (int i=0; i<n-gap; i++)
96+
{
97+
if (a[i] > a[i+gap])
98+
{
99+
swap(a[i], a[i+gap]);
100+
swapped = true;
101+
}
102+
}
103+
}
104+
}
105+
106+
int main()
107+
{
108+
int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
109+
int n = sizeof(a)/sizeof(a[0]);
110+
111+
combSort(a, n);
112+
113+
printf("Sorted array: \n");
114+
for (int i=0; i<n; i++)
115+
printf("%d ", a[i]);
116+
117+
return 0;
118+
}

0 commit comments

Comments
 (0)