Saturday, September 3, 2011

Bucket Sort


/* A program for bucket sort */
#include<stdlib.h>
#include<stdio.h>
#define MAX 5

typedef struct Q
{
int R,F;
int data[MAX];
}Q;

void initialise(Q *P);
int empty(Q *P);
int full(Q *P);
void enqueue(Q *P,int x);
int  dequeue(Q *P);

int main()
{ Q q[10];//10 queues are for ten buckets
int i,a[20],n,passes,passno,smallest,largest,divisor=10,qno;
for(i=0;i<10;i++)
initialise(&q[i]);
printf("\nEnter No of data : ");
scanf("%d",&n);
printf("\nEnter data to be sorted : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
/* find smallest and the largest number,largest will determine
  number of passes and negative numbers can be handled by
  subtracting the smallest from every number and after sorting
  same will be added to every number.
*/
smallest=largest=a[0];
for(i=1;i<n;i++)
 {
if(a[i]<smallest)
smallest=a[i];
if(a[i]>largest)
largest=a[i];
 }
for(i=0;i<n;i++)
a[i]-=smallest;
largest-=smallest;
//counting number of digits in largest
for(passes=0;largest>0;passes++)
largest=largest/10;
//bucket sort
for(passno=1;passno<=passes;passno++)
  {
     for(i=0;i<n;i++)
{
qno=a[i]%divisor/(divisor/10);
enqueue(&q[qno],a[i]);
}
     divisor=divisor*10;
     //recreate the list from elements in  queues
     i=0;
     for(qno=0;qno<10;qno++)
{
   while(!empty(&q[qno]))
a[i++]=dequeue(&q[qno]);
}
   }
     //display the sorted data
     printf("\nSorted data : ");
     for(i=0;i<n;i++)
printf("%d  ",a[i]+smallest);
   }

void initialise(Q *P)
{
int i;
P->R=-1;
P->F=-1;
}

int empty(Q *P)
{
if(P->R==-1)
return(1);
return(0);
}

int full(Q *P)
{
if(P->R==MAX-1)
return(1);
return(0);
}

void enqueue(Q *P,int x)
{       int i;

if(P->R==-1)
{
P->R=P->F=0;
P->data[P->R]=x;
}
else
{

P->R=P->R+1;
P->data[P->R]=x;
}
}

int  dequeue(Q *P)
{
int x;
x=P->data[P->F];
if(P->R==P->F)
{
P->R=-1;
P->F=-1;
}
else
P->F=P->F+1;
return(x);
}

No comments:

Post a Comment