fork download
  1. #include <stdio.h>
  2.  
  3. #include<limits.h>
  4.  
  5.  
  6.  
  7. //Function to find maximum element of the array
  8.  
  9. int max_element(int array[], int size)
  10.  
  11. {
  12.  
  13.  
  14. int max = INT_MIN;
  15.  
  16. for (int i = 0; i < size; i++)
  17.  
  18. {
  19.  
  20. //Updating max when array[i] is greater than max
  21.  
  22. if (array[i] > max)
  23.  
  24. max = array[i];
  25.  
  26. }
  27.  
  28. //return the max element
  29.  
  30. return max;
  31.  
  32. }
  33.  
  34.  
  35.  
  36. //Implementing bucket sort
  37.  
  38. void Bucket_Sort(int array[], int size)
  39.  
  40. {
  41.  
  42. //Finding max element of array which we will use to create buckets
  43.  
  44. int max = max_element(array, size);
  45.  
  46.  
  47.  
  48. // Creating buckets
  49.  
  50. int bucket[max+1];
  51.  
  52.  
  53.  
  54. //Initializing buckets to zero
  55.  
  56. for (int i = 0; i <= max; i++)
  57.  
  58. bucket[i] = 0;
  59.  
  60.  
  61.  
  62. // Pushing elements in their corresponding buckets
  63.  
  64. for (int i = 0; i < size; i++)
  65.  
  66. bucket[array[i]]++;
  67.  
  68.  
  69.  
  70. // Merging buckets effectively
  71.  
  72. int j=0; // j is a variable which points at the index we are updating
  73.  
  74. for (int i = 0; i <= max; i++)
  75.  
  76. {
  77.  
  78. // Running while loop until there is an element in the bucket
  79.  
  80. while (bucket[i] > 0)
  81.  
  82. {
  83.  
  84. // Updating array and increment j
  85.  
  86. array[j++] = i;
  87.  
  88.  
  89.  
  90. // Decreasing count of bucket element
  91.  
  92. bucket[i]--;
  93.  
  94. }
  95.  
  96. }
  97.  
  98. }
  99.  
  100.  
  101.  
  102.  
  103. int main()
  104.  
  105. {
  106.  
  107. int array[100] = {5, 10, 9, 8, 12};
  108. int i ;
  109. int num = 5;
  110.  
  111.  
  112.  
  113. printf("Enter the size of array: ");
  114.  
  115. //scanf("%d", &num);
  116.  
  117. printf("Enter the %d elements to be sorted:\n",num);
  118.  
  119. //for (i = 0; i < num; i++)
  120.  
  121. // scanf("%d", &array[i]);
  122.  
  123. printf("\nThe array of elements before sorting: \n");
  124.  
  125. for (i = 0; i < num; i++)
  126.  
  127. printf("%d ", array[i]);
  128.  
  129. printf("\nThe array of elements after sorting: \n");
  130.  
  131.  
  132.  
  133. // Calling bucket sort function
  134.  
  135. Bucket_Sort(array, num);
  136.  
  137. for (i = 0; i < num; i++)
  138.  
  139. printf("%d ", array[i]);
  140.  
  141. printf("\n");
  142.  
  143. return 0;
  144.  
  145. }
Success #stdin #stdout 0s 5436KB
stdin
Standard input is empty
stdout
Enter the size of array: Enter the 5 elements to be sorted:

The array of elements before sorting: 
5 10 9 8 12 
The array of elements after sorting: 
5 8 9 10 12