C program for Bucket sort algorithm

# C program for Bucket sort algorithm

3080
3
SHARE

C program for Bucket sort algorithm : Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. Let us see how Bucket sort works :

1. Set up an array of initially empty “buckets.”
2. Scatter: Go over the original array, putting each object in its bucket.
3. Sort each non-empty bucket.
4. Gather: Visit the buckets in order and put all elements back into the original array.

Now let us see how to write a for above logic of Bucket sort algorithm.

Note: Below code only works for positive .

### C program for Bucket Sort Algorithm :

```#include <conio.h>
#include <stdio.h>

int main( void )
{
int unsorted[50] , bucket[10][50]={{0}} , sorted[50] ;
int   j , k , m , p , flag = 0, num, N;
printf("\nEnter the number of elements to be sorted :");
scanf("%d",&N);
printf("\nEnter the elements to be sorted :\n");
for(k=0 ;  k < N ; k++){
scanf("\n%d",&num);
sorted[k] = unsorted[k] = num;
}

for(p=1; flag != N ; p*=10){

flag = 0;

for(k=0;k<N;k++){
bucket[(sorted[k]/p)%10][k] = sorted[k];
if ( (sorted[k]/p)%10  == 0 ){
flag++;
}
}

if (flag == N){
printf("\nSorted List: \n");
for(j=0 ;  j < N ; j++){
printf("%d\t", sorted[j]);
}
printf("\n");
getch();
return 0;
}

for(j=0,m=0;j<10;j++){
for(k=0;k<N;k++){
if( bucket[j][k] > 0 ){
sorted[m] = bucket[j][k];
bucket[j][k] = 0 ;
m++;
}
}
}

}

return 0 ;
}```

We hope you all have enjoyed the . If you have any doubts regarding above code, ask us in form of comments.

SHARE
Previous articleC program for Bogo sort algorithm
Next articleC program for quick sort algorithm
Well, I am software programmer and love to code. My hobbies is to do Hacking, Coding, Blogging, Web Designing and playing online games. Feel free to contact me at shiviskingg@gmail.com or lokesh@hackingloops.com