forked from avani112/HacktoberFest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBucket-sort.c
45 lines (45 loc) · 1.07 KB
/
Bucket-sort.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
#include <stdio.h>
int getMax(int a[], int n) // function to get maximum element from the given array
{
int max = a[0];
for (int i = 1; i < n; i++)
if (a[i] > max)
max = a[i];
return max;
}
void bucket(int a[], int n) // function to implement bucket sort
{
int max = getMax(a, n); //max is the maximum element of array
int bucket[max], i;
for (int i = 0; i <= max; i++)
{
bucket[i] = 0;
}
for (int i = 0; i < n; i++)
{
bucket[a[i]]++;
}
for (int i = 0, j = 0; i <= max; i++)
{
while (bucket[i] > 0)
{
a[j++] = i;
bucket[i]--;
}
}
}
void printArr(int a[], int n) // function to print array elements
{
for (int i = 0; i < n; ++i)
printf("%d ", a[i]);
}
int main()
{
int a[] = {54, 12, 84, 57, 69, 41, 9, 5};
int n = sizeof(a) / sizeof(a[0]); // n is the size of array
printf("Before sorting array elements are - \n");
printArr(a, n);
bucket(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
}