sorting of linked list using selection sort

This commit is contained in:
Rupeshiya 2018-02-04 18:26:36 +05:30 committed by GitHub
parent ebd939864e
commit 11ba39263e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,40 +1,89 @@
//sorting of linked list using selection sort
#include<stdio.h> #include<stdio.h>
struct node
{
int info;
struct node *link;
};
struct node *start=NULL;
//func to create node
struct node *createnode()
{
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
return(p);
}
//program to insert at begining
void insert()
{struct node *t;
t=createnode();
printf("\nenter the value to insert");
scanf("%d",&t->info);
if(start==NULL)
{start=t;
}
else
{strutc node *p;
p=start;
t->link=p;
start=t;
}
//program to sort the linked list using selection sort
void sort()
{
struct node *p,*t;
t=start;
int tmp;
for(t=start;t->link!=NULL;t=t->link)
{
for(p=t->link;p!=NULL;p=p->link)
{
if(t->info>p->info)
tmp=t->info;
t->info=p->info;
p->info=tmp;
}
}
//program to view sorted list
void viewlist()
{
struct node *p;
if(start==NULL)
{
printf("\nlist is empty");
}
else
{
p=start;
while(p!=NULL)
{
printf("%d",p->info);
p=p->link;
}
}
int main() int main()
{ {
int array[100], n, i, j, position, swap; int n;
whhile(1)
printf("Enter number of elements\n"); {
printf("\n1.insert value at beg");
printf("\n2.sort the list");
printf("\n3.view value");
printf("\nenter your choice");
scanf("%d",&n); scanf("%d",&n);
switch(n)
printf("Enter %d integers\n", n); {case 1:
insert();
for ( i = 0 ; i < n ; i++ ) break;
scanf("%d", &array[i]); case 2:
sort();
for ( i = 0 ; i < ( n - 1 ) ; i++ ) break;
{ case 3:
position = i; viewlist();
break;
for ( j = i + 1 ; j < n ; j++ ) default:
{ printf("\ninvalid choice");
if ( array[position] > array[j] )
position = j;
}
if ( position != i )
{
swap = array[i];
array[i] = array[position];
array[position] = swap;
} }
} }
return(0);
printf("Sorted list in ascending order:\n");
for ( i = 0 ; i < n ; i++ )
printf("%d\n", array[i]);
return 0;
} }