C program for Bucket sort algorithm

C program for Bucket sort algorithm

2057
2
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.

2 COMMENTS

LEAVE A REPLY