Created
March 9, 2019 16:23
-
-
Save luk0y/d29ff9c7912a0294ce5bb05bcff2bb75 to your computer and use it in GitHub Desktop.
Sorting a linked list using bubble sort algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
struct node | |
{ | |
struct node *addr; | |
int data; | |
}; | |
void main() | |
{ | |
struct node *start=NULL,*nn,*ptr,*next; | |
int x,y,n=0,temp=0,i,j=0; | |
int count=0; | |
char chra; | |
hq: | |
printf("Enter the nodes you want : "); | |
scanf("%d",&y); | |
if(y>0){ | |
int k=y; | |
printf("\nEnter the values :\n"); | |
while(y!=0) | |
{ | |
scanf("%d",&x); | |
nn=(struct node*) malloc(sizeof(struct node)); | |
if(nn==NULL) | |
{ | |
printf("no space"); | |
} | |
else | |
{ | |
n=n+1; | |
if(start==NULL) | |
{ | |
start=nn; | |
nn->data=x; | |
nn->addr=NULL; | |
} | |
else | |
{ | |
ptr=start; | |
while(ptr->addr!=NULL) | |
{ | |
ptr=ptr->addr; | |
} | |
ptr->addr=nn; | |
nn->data=x; | |
nn->addr=NULL; | |
} | |
} | |
y--; | |
} | |
ptr=start; | |
printf("Linked list : \n"); | |
while(ptr!=NULL) | |
{ | |
printf("%d\n",ptr->data); | |
ptr=ptr->addr; | |
} | |
printf("\n\n"); | |
for(i=1;i<k;i++) | |
{ | |
ptr=start; | |
next=ptr->addr; | |
for(j=0;j<(k-i);j++) | |
{ | |
if(ptr->data < next->data) | |
{ | |
temp=ptr->data; | |
ptr->data=next->data; | |
next->data=temp; | |
} | |
ptr=next; | |
next=next->addr; | |
} | |
} | |
ptr=start; | |
printf("Sorted ones : \n"); | |
while(ptr!=NULL) | |
{ | |
printf("%d\n",ptr->data); | |
ptr=ptr->addr; | |
} | |
} | |
else | |
{ | |
printf("\nNo Node created press y to create list or enter n to exit %d: ", y); | |
scanf("%c",&chra); | |
if(chra=='o'){ | |
goto hq; | |
} | |
else | |
{ | |
printf("\nBye Bye\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment