//How to perform Bubble Sort on Array created dynamically.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
main()
{
struct node *start=NULL,*start1=NULL,*start2=NULL;
int n,m;
void create(struct node **, int);
void show(struct node *);
void bubsort(struct node *);
printf("\nEnter the number of elements you want in your first linked list :");
scanf("%d",&m);
create(&start,m);
printf("\nlinked list is :\n");
show(start);
bubsort(start);
printf("\nlinked list after sorting :\n");
show(start);
getch();
}
void create(struct node **q,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the %d element :",i);
scanf("%d",&(p->data));
p->next=NULL;
if(*q==NULL)
*q=p;
else
lst->next=p;
lst=p;
}
}
void show(struct node *start)
{
while(start!=NULL)
{
printf(" %d",start->data);
start=start->next;
}
}
void bubsort(struct node *start)
{
struct node *ptr1,*ptr2,*t=NULL;
int temp;
ptr1=start;
if(ptr1==NULL)
{
printf("\nList is empty");
return;
}
while(ptr1->next!=NULL)
{
ptr2=start;
while(ptr2->next!=t)
{
if(ptr2->data>(ptr2->next)->data)
{
temp= ptr2->data;
ptr2->data=(ptr2->next)->data;
(ptr2->next)->data=temp;
}
ptr2=ptr2->next;
}
t=ptr2;
ptr1=ptr1->next;
}
}
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
main()
{
struct node *start=NULL,*start1=NULL,*start2=NULL;
int n,m;
void create(struct node **, int);
void show(struct node *);
void bubsort(struct node *);
printf("\nEnter the number of elements you want in your first linked list :");
scanf("%d",&m);
create(&start,m);
printf("\nlinked list is :\n");
show(start);
bubsort(start);
printf("\nlinked list after sorting :\n");
show(start);
getch();
}
void create(struct node **q,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the %d element :",i);
scanf("%d",&(p->data));
p->next=NULL;
if(*q==NULL)
*q=p;
else
lst->next=p;
lst=p;
}
}
void show(struct node *start)
{
while(start!=NULL)
{
printf(" %d",start->data);
start=start->next;
}
}
void bubsort(struct node *start)
{
struct node *ptr1,*ptr2,*t=NULL;
int temp;
ptr1=start;
if(ptr1==NULL)
{
printf("\nList is empty");
return;
}
while(ptr1->next!=NULL)
{
ptr2=start;
while(ptr2->next!=t)
{
if(ptr2->data>(ptr2->next)->data)
{
temp= ptr2->data;
ptr2->data=(ptr2->next)->data;
(ptr2->next)->data=temp;
}
ptr2=ptr2->next;
}
t=ptr2;
ptr1=ptr1->next;
}
}