Monday, 2 May 2016

How to implement Bucket (Bin) sort ?



  • Distribute the elements into a number of buckets
  • Each bucket is then sorted individually (using any type of sorting algo)
  • Elements are distributed among bins

       


  • Elements are sorted within each bin

        


Implementation
/**
 * Initialize the Bucket array to store elements
 **/
int maxVal = 5;
int [] bucket new int[maxVal+1];

for (int i=0; i<bucket.lengthi++) {
    bucket[i]=0;
}

/**
 * Element as index and
 * value stored at array index is occurrence
 **/
for (int i=0; i<array.lengthi++) {
    bucket[array[i]]++;
}

/**
 * Restore all the elements in sorted order
 **/
int outPos = 0;

for (int i=0; i<bucket.lengthi++) {  // iterate through buckets
   for (int j=0; j<bucket[i]; j++) {
       array[outPos++]=i;
   }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.