C program to display sorted list using Bucket sort

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.

  1. /*
  2.  * C Program to Sort Array using Bucket Sort
  3.  */
  4. #include <stdio.h>
  5.  
  6. /* Function for bucket sort */
  7. void Bucket_Sort(int array[], int n)
  8. {  
  9.     int i, j;  
  10.     int count[n]; 
  11.     for (i = 0; i < n; i++)
  12.         count[i] = 0;
  13.  
  14.     for (i = 0; i < n; i++)
  15.         (count[array[i]])++;
  16.  
  17.     for (i = 0, j = 0; i < n; i++)  
  18.         for(; count[i] > 0; (count[i])--)
  19.             array[j++] = i;
  20. }   
  21. /* End of Bucket_Sort() */
  22.  
  23. /* The main() begins */
  24. int main()
  25. {
  26.     int array[100], i, num; 
  27.  
  28.     printf("Enter the size of array : ");   
  29.     scanf("%d", &num);   
  30.     printf("Enter the %d elements to be sorted:\n",num); 
  31.     for (i = 0; i < num; i++)
  32.         scanf("%d", &array[i]); 
  33.     printf("\nThe array of elements before sorting : \n");
  34.     for (i = 0; i < num; i++)
  35.         printf("%d ", array[i]);  
  36.     printf("\nThe array of elements after sorting : \n"); 
  37.     Bucket_Sort(array, num); 
  38.     for (i = 0; i < num; i++)
  39.         printf("%d ", array[i]);   
  40.     printf("\n");     
  41.     return 0;
  42. }

$ 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
advertisement
If you wish to look at all C Algorithms and Solutions, go to C Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.