Here you will get program for bucket sort in C and C++.

In bucket sort algorithm the array elements are distributed into a number of buckets. Then each bucket sorted individually either using any other sorting algorithm or by recursively applying bucket sort.

Take example shown in below image.

Elements are distributed among buckets

Then, elements are sorted within each bucket

Below is the program to implement this algorithm. In this program it is assumed that the array elements are between 0 to 10.

## Program for Bucket Sort in C

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include<stdio.h> #define SIZE 10 void bucketSort(int a[], int n) { int i, j, k, buckets[SIZE]; for(i = 0; i < SIZE; ++i) buckets[i] = 0; for(i = 0; i < n; ++i) ++buckets[a[i]]; for(i = 0, j = 0; j < SIZE; ++j) for(k = buckets[j]; k > 0; --k) a[i++] = j; } int main() { int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8; printf("Before sorting:\n"); for(i = 0; i < n; ++i) printf("%d ", a[i]); bucketSort(a, n); printf("\n\nAfter sorting:\n"); for(i = 0; i < n; ++i) printf("%d ", a[i]); return 0; } |

## Program for Bucket Sort in C++

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include<iostream> #define SIZE 10 using namespace std; void bucketSort(int a[], int n) { int i, j, k, buckets[SIZE]; for(i = 0; i < SIZE; ++i) buckets[i] = 0; for(i = 0; i < n; ++i) ++buckets[a[i]]; for(i = 0, j = 0; j < SIZE; ++j) for(k = buckets[j]; k > 0; --k) a[i++] = j; } int main() { int i, a[] = {3, 6, 5, 1, 8, 4, 3, 1}, n = 8; cout << "Before sorting:\n"; for(i = 0; i < n; ++i) cout << a[i] << " "; bucketSort(a, n); cout<< "\n\nAfter sorting:\n"; for(i = 0; i < n; ++i) cout<< a[i] << " "; return 0; } |

**Output**

*Before sorting:*

*3 6 5 1 8 4 3 1*

*After sorting:*

*1 1 3 3 4 5 6 8*

what does it mean ++buckets[a[i]]; !?

there is mistake in c++ program which is value is SIZE is not given

SIZE is a preprocessor directive

ohh…hello it’s not bucket sort ,your coding is almost like counting sort……….u r making a fool of us …..first learn what bucket sort is okk

This is not working at all. I changed the values in the array and no sorting takes place

This is not Bucket Sort but Counting Sort – the difference is that in Counting Sort you count how much times the number appears in array (like in your code) which is good for integers but bad for floats. Bucket Sort works with floats – it creates “buckets” – array of lists, divide elements by liknking them to appropriate lists (that every element in list a[i-1] are lower than element in list a[i], every elements in list a[i] are lower than every element in list a[i+1] etc.) next you sort elements in lists using whatever you want (there are few elements than this can be Insertion Sort – will be fast) and then you rewrite sorted elements form lists back to array.