HomePOSTBucket Sort program in C Language

# Bucket Sort program in C Language

Bucket Sort program in C Language algorithm implementation –  Bucket sort is a sorting algorithm that separate the elements into multiple groups said to be buckets. Elements in sort are first uniformly divided into groups called bucket sorting algorithm , and then they are sorted by any other sorting algorithm.

## Complexity of bucket sort is:

• Best and Average case O(n + k),
• worst case complexity O(n2)
• where n is the number of items.

In this program user would be asked to enter the number of elements along with the element values and then the programs would sort them in ascending order by using merge sorting algorithm logic.

## Bucket Sort algorithm C Program implementation

``````#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[] = {51, 1, 8, 5, 6, 4, 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);
}  ``````

## OUTPUT

``````Before sorting array elements are
51, 1, 8, 5, 6, 4, 9, 5

After sorting array elements are
1, 4, 5, 5, 6, 8, 9, 51 ``````

#### you can read more articles like this here.

If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.❤

RELATED ARTICLES