Skip to content

Commit 8fc0552

Browse files
authored
Create CombSort.cpp
1 parent 838340a commit 8fc0552

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

CombSort.cpp

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// C++ CombSor
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
//for finding gap between elements
6+
int getNextGap(int gap)
7+
{
8+
// Shrink
9+
gap = (gap*10)/13;
10+
if (gap < 1)
11+
return 1;
12+
return gap;
13+
}
14+
// Function to sort a[0..n-1] using Comb Sort
15+
void combSort(int a[], int n)
16+
{
17+
// Initialize gap
18+
int gap = n;
19+
// Initialize swapped as true to make sure that
20+
// loop runs
21+
bool swapped = true;
22+
// continues while gap is more than 1 and last
23+
// iteration caused a swap
24+
while (gap != 1 || swapped == true)
25+
{
26+
// Find next gap
27+
gap = getNextGap(gap);
28+
// Initialize swapped as false so that we can
29+
// check if swap happened or not
30+
swapped = false;
31+
// Compare all elements with current gap
32+
for (int i=0; i<n-gap; i++)
33+
{
34+
if (a[i] > a[i+gap])
35+
{
36+
swap(a[i], a[i+gap]);
37+
swapped = true;
38+
}
39+
}
40+
}
41+
}
42+
//main funct
43+
int main()
44+
{
45+
int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
46+
int n = sizeof(a)/sizeof(a[0]);
47+
combSort(a, n);
48+
printf("Sorted array: \n");
49+
for (int i=0; i<n; i++)
50+
printf("%d ", a[i]);
51+
52+
return 0;
53+
}

0 commit comments

Comments
 (0)