forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comb.c
95 lines (71 loc) · 1.97 KB
/
comb.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
COMB SORT :
Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values.
So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size
more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration
until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap
and performs better than Bubble Sort.
*/
#include <stdio.h>
void comb_sort(int *ar, int n){
//gap variable gives gap between the values to compare
int gap = n;
int q,w;
while(gap>1){
//updating the gap variable
gap = gap/1.3;
if(gap<1){
gap = 1;
}
q=0;w=q+gap;
while(w<n){
if(ar[q]>ar[w]){
//swap values
int temp = ar[q];
ar[q] = ar[w];
ar[w] = temp;
}
w++;q++;
}
}
}
int main()
{
int n;
int *ar;
printf("Enter the limit : ");
//Input the number of elements to be sorted
scanf("%d",&n);
//Dynamically allocate memory for the array
ar = (int*)malloc(n * sizeof(int));
//Input numbers to be sorted
for(int i=0;i<n;i++){
scanf("%d",&ar[i]);
}
printf("Unsorted array : \n");
//Print the unsorted array
for(int i=0;i<n;i++){
printf("%d ",ar[i]);
}
printf("\n\n");
//Execute the comb sort function
comb_sort(ar, n);
printf("Sorted array : \n");
//Print the sorted array
for(int i=0;i<n;i++){
printf("%d ",ar[i]);
}
return 0;
}
/*
CASE 1:
input = [1, 8, 7, 61, 5, 4, 11];
EXPECTED: [1,4,5,7,8,11,61]
CASE 2:
input = [1,8,3,9,10,10,2,4];
EXPECTED: [1,2,3,4,8,9,10,10]
Time Complexity - O(n log n) for the best case.
O(n^2/2^p) (p is a number of increment) for average case.
O(n^2) for the worst case.
Space Complexity - O(1)
*/