Program code for bubble sort using linked list
//code for bubble sort using linked list
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
typedef struct linked
{
int val;
struct linked *next;
}lnk;
lnk *create();
void bubblesort(lnk *);
void disp(lnk *);
void main()
{
lnk *h;
printf("\n\nEnter the values (0 to exit) : ");
h=create();
printf("\n\nValues in the linked list before sorting are : ");
disp(h);
bubblesort(h);
printf("\n\nValues in the linked list after sorting are : ");
disp(h);
getch();
}
lnk *create()
{
lnk *temp,*ptr,*h=NULL;
int v;
while(1)
{
scanf("%d",&v);
if(v==0)
return h;
temp=(lnk*)malloc(sizeof(lnk));
temp->val=v;
temp->next=NULL;
if(h==NULL)
h=temp;
else
ptr->next=temp;
ptr=temp;
}
}
void disp(lnk *h)
{
while(h!=NULL)
{
printf("%d",h->val);
h=h->next;
}
}
void bubblesort(lnk *h)
{
int v;
lnk *ptr,*loc;
loc=h;
while(h!=NULL)
{
ptr=loc;
while(ptr->next->next!=NULL)
{
if(ptr->val>ptr->next->val)
{
v=ptr->val;
ptr->val=ptr->next->val;
ptr->next->val=v;
}
ptr=ptr->next;
}
if(ptr->val>ptr->next->val)
{
v=ptr->val;
ptr->val=ptr->next->val;
ptr->next->val=v;
}
h=h->next;
}
}
I/O :
Enter the values (0 to exit) : 5 4 3 2 1 7 6 9 8 0
Values in the linked list before sorting are : 5 4 3 2 1 7 6 9 8
Values in the linked list after sorting are : 1 2 3 4 5 6 7 8 9
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
typedef struct linked
{
int val;
struct linked *next;
}lnk;
lnk *create();
void bubblesort(lnk *);
void disp(lnk *);
void main()
{
lnk *h;
printf("\n\nEnter the values (0 to exit) : ");
h=create();
printf("\n\nValues in the linked list before sorting are : ");
disp(h);
bubblesort(h);
printf("\n\nValues in the linked list after sorting are : ");
disp(h);
getch();
}
lnk *create()
{
lnk *temp,*ptr,*h=NULL;
int v;
while(1)
{
scanf("%d",&v);
if(v==0)
return h;
temp=(lnk*)malloc(sizeof(lnk));
temp->val=v;
temp->next=NULL;
if(h==NULL)
h=temp;
else
ptr->next=temp;
ptr=temp;
}
}
void disp(lnk *h)
{
while(h!=NULL)
{
printf("%d",h->val);
h=h->next;
}
}
void bubblesort(lnk *h)
{
int v;
lnk *ptr,*loc;
loc=h;
while(h!=NULL)
{
ptr=loc;
while(ptr->next->next!=NULL)
{
if(ptr->val>ptr->next->val)
{
v=ptr->val;
ptr->val=ptr->next->val;
ptr->next->val=v;
}
ptr=ptr->next;
}
if(ptr->val>ptr->next->val)
{
v=ptr->val;
ptr->val=ptr->next->val;
ptr->next->val=v;
}
h=h->next;
}
}
I/O :
Enter the values (0 to exit) : 5 4 3 2 1 7 6 9 8 0
Values in the linked list before sorting are : 5 4 3 2 1 7 6 9 8
Values in the linked list after sorting are : 1 2 3 4 5 6 7 8 9
Comments
Post a Comment