Problem:
n students have marks and names. Rank students based on their marks and print their names.
#include <stdio.h>
#include <assert.h>
struct student
{
int marks;
char name[50];
};
struct listnode
{
struct student * data;
struct listnode *next;
};
addtofrontoflist(struct listnode *listhead,struct student *node)
{
//make a block of listnode.
struct listnode bucketnode;
bucketnode.data=node;
struct listnode *tmp;
tmp=listhead->next;
listhead->next=&bucketnode;
bucketnode.next=tmp;
}
bucket_sort(struct student array[],int n)
{
struct listnode *buckets[n];
int i,j;
struct listnode *temp;
for(i=0;i<n;i++)
{
buckets[i]=malloc(sizeof(struct listnode));
assert(buckets[i]!=NULL);
}
for(i=0;i<n;i++)
{
addtofrontoflist(buckets[array[i].marks],&array[i]);
}
for(i=0;i<n;i++)
{
if(buckets[i]==NULL) continue;
for(temp=buckets[i];temp!=NULL;temp++)
printf("%d %s\n",temp->data->marks,temp->data->name);
}
}
main()
{
struct student array[5]={"1,one","2,two","2,two","4,four","1,one"};
bucket_sort(array,5);
}