forked from The-Streamliners/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombSort.cpp
More file actions
59 lines (39 loc) · 987 Bytes
/
Copy pathcombSort.cpp
File metadata and controls
59 lines (39 loc) · 987 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//It's basically Bubble sort with some improvements
//But the time complexity is still O(n^2)
#include<bits/stdc++.h>
using namespace std;
int getNextGap(int gap) // Shriks gap by 1.3 (found by testing on large number of inputs)
{
gap = (gap*10)/13;
if (gap < 1)
return 1;
return gap;
}
void combSort(int a[], int n) //the sorting function
{
int gap = n;
bool swapped = true;
while (gap != 1 || swapped == true) //while the gap is greater than 1
{
gap = getNextGap(gap); //shrink the gap using the above function
swapped = false;
for (int i=0; i<n-gap; i++)
{
if (a[i] > a[i+gap])
{
swap(a[i], a[i+gap]);
swapped = true;
}
}
}
}
int main()
{
int a[] = {100, 6, -5, 2, 87, 69, -65, 0, 8};
int n = sizeof(a)/sizeof(a[0]);
combSort(a, n);
printf("Sorted array: \n");
for (int i=0; i<n; i++)
printf("%d ", a[i]);
return 0;
}