Skip to content

Commit 984120a

Browse files
Merge pull request iam-abbas#360 from muskan077/c++
Comb_sort.cpp
2 parents f3d5731 + 404b5ad commit 984120a

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Sorting Algorithm/comb_sort.cpp

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// C++ implementation of Comb Sort
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
// To find gap between elements
6+
int getNextGap(int gap)
7+
{
8+
// Shrink gap by Shrink factor
9+
gap = (gap*10)/13;
10+
11+
if (gap < 1)
12+
return 1;
13+
return gap;
14+
}
15+
16+
// Function to sort a[0..n-1] using Comb Sort
17+
void combSort(int a[], int n)
18+
{
19+
// Initialize gap
20+
int gap = n;
21+
22+
// Initialize swapped as true to make sure that
23+
// loop runs
24+
bool swapped = true;
25+
26+
// Keep running while gap is more than 1 and last
27+
// iteration caused a swap
28+
while (gap != 1 || swapped == true)
29+
{
30+
// Find next gap
31+
gap = getNextGap(gap);
32+
33+
// Initialize swapped as false so that we can
34+
// 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+
// Driver program
50+
int main()
51+
{
52+
int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
53+
int n = sizeof(a)/sizeof(a[0]);
54+
55+
combSort(a, n);
56+
57+
printf("Sorted array: \n");
58+
for (int i=0; i<n; i++)
59+
printf("%d ", a[i]);
60+
61+
return 0;
62+
}
63+

0 commit comments

Comments
 (0)