forked from amanss00/ForNewbies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sorting Algorithm.c
196 lines (176 loc) · 2.91 KB
/
Sorting Algorithm.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#include<stdio.h>
#include<limits.h>
#include<stdlib.h>
void swap(int *x,int *y)
{
int temp = *y;
*y = *x;
*x = temp;
}
void Bubble(int A[],int n)
{
int i,j,flag=0;
for(i=0;i<n-1;i++)
{
for ( j = 0; j < n-1-i; j++)
{
if(A[j]>A[j+1])
swap(&A[j],&A[j+1]);
flag=1;
}
if(flag==0)
break;
}
}
void Insertion(int A[],int n)
{
int i,j,x;
for (i = 1; i < n; i++)
{
j = i-1;
x=A[i];
while(j> -1 && A[j]>x)
{
A[j+1]=A[j];
j-- ;
}
A[j+1] = x;
}
}
void SelectionSort(int A[],int n)
{
int i,j,k;
for(i=0;i<n;i++)
{
for(j=k=i;j<n;j++){
if(A[j]<A[k])
k=j;
}
swap(&A[i],&A[k]);
}
}
int partition(int A[],int l,int h)
{
int pivot = A[l];
int i=l,j=h;
do
{
do{i++; } while (A[i]<=pivot);
do{j--; } while (A[j]>pivot);
if(i<j)
swap(&A[i],&A[j]);
} while (i<j);
swap(&A[l],&A[j]);
return j;
}
void QuickSort(int A[],int l,int h)
{
int j;
if(l<h)
{
j = partition(A,l,h);
QuickSort(A,l,j);
QuickSort(A,j+1,h);
}
}
void merge(int A[],int l,int mid,int h)
{
int i=l,j=mid+1,k=l;
int B[100];
while(i<=mid && j<=h)
{
if(A[i]<A[j])
B[k++]=A[i++];
else
B[k++]=A[j++];
}
for(;i<=mid;i++)
B[k++]=A[i];
for(;j<=h;j++)
B[k++]=A[j];
for(i=l;i<=h;i++)
A[i]=B[i];
}
void IMergeSort(int A[],int n)
{
int p,l,h,mid,i;
for(p=2;p<=n;p=p*2)
{
for(i=0;i+p-1<n;i=i+p)
{
l=i;
h=i+p-1;
mid=(l+h)/2;
merge(A,l,mid,h);
}
if(n-i>p/2)
{
l = i;
h = i+p-1;
mid = (l+h)/2;
merge(A, l, mid, n-1);
}
}
if(p/2<n)
{
merge(A,0,p/2-1,n-1);
}
}
void MergeSort(int A[],int l,int h)
{
int mid;
if(l<h)
{
mid = (l+h)/2;
MergeSort(A,l,mid);
MergeSort(A,mid+1,h);
merge(A,l,mid,h);
}
}
int findMax(int A[],int n){
int max=INT_MIN;
for(int i=0;i<n;i++)
{
if(A[i]>max)
max= A[i];
}
return max;
}
void CountSort(int A[],int n)
{
int i,j,max,*C;
max=findMax(A,n);
C=(int *)malloc(sizeof(int)*(max+1));
for (i = 0; i < max+1; i++)
{
C[i]=0;
}
for(i=0;i<n;i++)
{
C[A[i]]++;
}
i=0;j=0;
while(j<max+1)
{
if(C[j]>0)
{
A[i++]=j;
C[j]--;
}
else{
j++;
}
}
}
int main()
{
int A[]={3,7,9,10,6,5,12,4,11,24};
int n=10;
//Use respective function to use sorting of your choice
for (int i = 0; i < 10; i++)
{
printf("%d ",A[i]);
}
printf("\n");
return 0;
}