/* Given k list of integers M1, M2,
M3,.........., Mk. Write a program to produce one
complete sorted list of integers combining these k list */
#include<stdio.h>
#include<malloc.h>
struct list
{
int
item;
struct
list *next;
};
typedef struct list node;
node* bsort(node*,int);
int main()
{
node *root[20],*p,*q;
int *list_size,K,i,j,SIZE=0;
printf("\n Enter the number
of lists to be formed:");
scanf("%d",&K);
list_size=(int
*)malloc(K*sizeof(int));
for(i=1;i<=K;i++)
{
printf("\n
Enter the size of list %d# ",i);
scanf("%d",(list_size+i));
SIZE+=*(list_size+i);
root[i]=(node
*)malloc(sizeof(node));
q=root[i];
printf("\n
Enter the elements of list %d# ",i);
scanf("%d",&q->item);
for(j=1;j<*(list_size+i);j++)
{
q->next=(node
*)malloc(sizeof(node));
q=q->next;
scanf("%d",&q->item);
}
q->next=NULL;
printf("\n");
}
for(i=1;i<=K;i++)
{
q=root[i];
printf("\n
Elements of List M[%d]: ",i);
while(q!=NULL)
{printf("%d
",q->item);
q=q->next;
}
printf("\n");
}
for(i=1;i<=K;i++)
root[i]=bsort(root[i],*(list_size+i));
for(i=1;i<=K;i++)
{
q=root[i];
printf("\n
Elements of List M[%d] after sorting: ",i);
while(q!=NULL)
{printf("%d
",q->item);
q=q->next;
}
printf("\n");
}
q=root[1];
for(i=1;i<K;i++)
{
while(root[i]->next!=NULL)
root[i]=root[i]->next;
root[i]->next=root[i+1];
root[i]=root[i]->next;
}
q=bsort(q,SIZE);
printf("\n Final List after
merging:\n");
while(q!=NULL)
{
printf("
%d ",q->item);
q=q->next;
}
return 0;
}
node* bsort(node *head,int size)
{
int
i,j,hold;
node
*tmp;
tmp=head;
for(i=0;i<size-1;i++)
{
for(j=0;j<size-i-1;j++)
{
if(tmp->item<tmp->next->item)
{
hold=tmp->item;
tmp->item=tmp->next->item;
tmp->next->item=hold;
}
tmp=tmp->next;
}
tmp=head;
}
return(head);
}
No comments:
Post a Comment