This C program sorts elements of an integer array using Bucket sort. This is a linear time algorithm.
Here is the source code of the C program to display sorted list using Bucket sort. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Sort Array using Bucket Sort
*/
#include <stdio.h>
/* Function for bucket sort */
void Bucket_Sort(int array[], int n)
{
int i, j;
int count[n];
for (i = 0; i < n; i++)
count[i] = 0;
for (i = 0; i < n; i++)
(count[array[i]])++;
for (i = 0, j = 0; i < n; i++)
for(; count[i] > 0; (count[i])--)
array[j++] = i;
}
/* End of Bucket_Sort() */
/* The main() begins */
int main()
{
int array[100], i, num;
printf("Enter the size of array : ");
scanf("%d", &num);
printf("Enter the %d elements to be sorted:\n",num);
for (i = 0; i < num; i++)
scanf("%d", &array[i]);
printf("\nThe array of elements before sorting : \n");
for (i = 0; i < num; i++)
printf("%d ", array[i]);
printf("\nThe array of elements after sorting : \n");
Bucket_Sort(array, num);
for (i = 0; i < num; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}
$ gcc bucket_sort.c $ a.out Enter How many Numbers : 10 Enter the 10 elements to be sorted:8 1 3 2 1 5 4 9 6 7 The array of elements before sorting : 8 1 3 2 1 5 4 9 6 7 The array of elements after sorting : 1 1 2 3 4 5 6 7 8 9
Sanfoundry Global Education & Learning Series – 1000 C Algorithms.
advertisement
If you wish to look at all C Algorithms and Solutions, go to C Algorithms.
Related Posts:
- Apply for Computer Science Internship
- Practice BCA MCQs
- Apply for C Internship
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs