Skip to content

Commit 29c8f08

Browse files
committed
Added Comb Sort in C
1 parent 9583c51 commit 29c8f08

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

sortingAlgo/combSort/a.out

16.5 KB
Binary file not shown.

sortingAlgo/combSort/combSort.c

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// C implementation of Comb Sort
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
#include <stdbool.h>
5+
6+
// To find gap between elements
7+
int getNextGap(int gap)
8+
{
9+
// Shrink gap by Shrink factor
10+
gap = (gap * 10) / 13;
11+
12+
if (gap < 1)
13+
return 1;
14+
return gap;
15+
}
16+
17+
// Function to sort a[0..n-1] using Comb Sort
18+
void combSort(int a[], int n)
19+
{
20+
// Initialize gap
21+
int gap = n;
22+
23+
// Initialize swapped as true to make sure that
24+
// loop runs
25+
bool swapped = true;
26+
27+
// Keep running while gap is more than 1 and last
28+
// 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
35+
// check if swap happened or not
36+
swapped = false;
37+
38+
// Compare all elements with current gap
39+
for (int i = 0; i < n - gap; i++)
40+
{
41+
if (a[i] > a[i + gap])
42+
{
43+
int temp = a[i];
44+
a[i] = a[i + gap];
45+
a[i + gap] = temp;
46+
swapped = true;
47+
}
48+
}
49+
}
50+
}
51+
52+
// Driver program
53+
int main()
54+
{
55+
int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
56+
int n = sizeof(a) / sizeof(a[0]);
57+
58+
combSort(a, n);
59+
60+
printf("Sorted array: \n");
61+
for (int i = 0; i < n; i++)
62+
printf("%d ", a[i]);
63+
64+
return 0;
65+
}

0 commit comments

Comments
 (0)