Skip to content

Commit f4dcfb1

Browse files
authored
Create bucket_sort.c
1 parent e6d1013 commit f4dcfb1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

C/bucket_sort.c

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Bucket Sort in C programming
2+
#include <stdio.h>
3+
int getMax(int array[], int size)
4+
{
5+
int max = array[0];
6+
for (int i = 1; i < size; i++)
7+
if (array[i] > max)
8+
max = array[i];
9+
return max;
10+
}
11+
void bucketSort(int array[], int size)
12+
{
13+
// The size of bucket must be at least the (max+1) but
14+
// we cannot assign declare it as int bucket(max+1) in C as
15+
// it does not support dynamic memory allocation.
16+
// So, its size is provided statically.
17+
int bucket[10];
18+
const int max = getMax(array, size);
19+
for (int i = 0; i <= max; i++)
20+
{
21+
bucket[i] = 0;
22+
}
23+
for (int i = 0; i < size; i++)
24+
{
25+
bucket[array[i]]++;
26+
}
27+
for (int i = 0, j = 0; i <= max; i++)
28+
{
29+
while (bucket[i] > 0)
30+
{
31+
array[j++] = i;
32+
bucket[i]--;
33+
}
34+
}
35+
}
36+
void printArray(int array[], int size)
37+
{
38+
for (int i = 0; i < size; ++i)
39+
{
40+
printf("%d ", array[i]);
41+
}
42+
printf("\n");
43+
}
44+
int main()
45+
{
46+
int data[] = {4, 3, 4, 5, 6, 0, 9, 5};
47+
int size = sizeof(data) / sizeof(data[0]);
48+
bucketSort(data, size);
49+
printf("Sorted array in ascending order: \n");
50+
printArray(data, size);
51+
}

0 commit comments

Comments
 (0)