Skip to content

Commit 2d5e89c

Browse files
authored
Comb-sort.cpp
Comb-sort or advanced bubble sort implementation in cpp.
1 parent 6511911 commit 2d5e89c

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Comb-sort

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*Refrences: https://w...content-available-to-author-only...s.org/comb-sort/
2+
* https://e...content-available-to-author-only...a.org/wiki/Comb_sort
3+
*/
4+
/*
5+
*Time complexicity: Worst Case O(n^2) - Best Case O(n)
6+
*Space Complexicity: O(1)
7+
*/
8+
#include<bits/stdc++.h>
9+
using namespace std;
10+
11+
// To find gap between elements
12+
int getNextGap(int gap)
13+
{
14+
// Shrink gap by Shrink factor
15+
gap = (gap*10)/13;
16+
17+
if (gap < 1)
18+
return 1;
19+
return gap;
20+
}
21+
22+
// Function to sort a[0..n-1] using Comb Sort
23+
void combSort(int a[], int n)
24+
{
25+
// Initialize gap
26+
int gap = n;
27+
28+
// Initialize swapped as true to make sure that
29+
// loop runs
30+
bool swapped = true;
31+
32+
// Keep running while gap is more than 1 and last
33+
// iteration caused a swap
34+
while (gap != 1 || swapped == true)
35+
{
36+
// Find next gap
37+
gap = getNextGap(gap);
38+
39+
// Initialize swapped as false so that we can
40+
// check if swap happened or not
41+
swapped = false;
42+
43+
// Compare all elements with current gap
44+
for (int i=0; i<n-gap; i++)
45+
{
46+
if (a[i] > a[i+gap])
47+
{
48+
swap(a[i], a[i+gap]);
49+
swapped = true;
50+
}
51+
}
52+
}
53+
}
54+
55+
// Driver code
56+
int main()
57+
{
58+
int arr[] = {123, 512, 1, 13, 12, -20, 22, -2134, 28, 12, 123, 90, 0};
59+
int n = sizeof(arr)/sizeof(arr[0]);
60+
61+
combSort(arr, n);
62+
63+
printf("Sorted array: \n");
64+
for (int i=0; i<n; i++)
65+
printf("%d ", arr[i]);
66+
//-2134 -20 0 1 12 12 13 22 28 90 123 123 512
67+
return 0;
68+
}
69+

0 commit comments

Comments
 (0)