Monday, April 4, 2016

C program to implement sorting in link list

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
 int info;
 struct node* ptr;
}*START;
void create()
{
 int n;
 struct node *temp;
 temp=(struct node*)malloc(sizeof(node));
 if(temp==NULL)
  {
   printf("Memory not available");
  }
 printf("Enter data to enter");
 scanf("%d",&n);
 temp->info=n;
 temp->ptr=NULL;
 if(START==NULL)
  {
   START=temp;
  }
 else
  {
   struct node *t =START;
   while(t->ptr!=NULL)
    {
     t=t->ptr;
    }
   t->ptr=temp;
  }
}
void display()
{
 struct node *t=START;
 printf("\n");
 while(t!=NULL)
  {
   printf("%d ",t->info);
   t=t->ptr;
  }
}
void sort()
{
 struct node *t1=START;
 struct node *t2;
 int count=0;
 int i=0,j;
 while(t1!=NULL)
 {
  count++;
  t1=t1->ptr;
 }
 for(i=0;i<count;i++)
  {
   t1=START;
   for(j=0;j<count-i-1;j++)
    {
      if(t1->info>(t1->ptr)->info)
       {
int temp=t1->info;
t1->info=(t1->ptr)->info;
(t1->ptr)->info=temp;
       }
       t1=t1->ptr;
    }
  }
}
void main()
{
 START=NULL;
 int ch;
 do
 {
  printf("\nEnter choice 1.Insert 2.display 3.Sort 4.Exit");
  scanf("%d",&ch);
  switch(ch)
   {
    case 1:
     create();
     break;
    case 2:
     display();
     break;
    case 3:
     sort();
     break;
    case 4:
     exit(0);
     break;
   }
 }while(ch!=4);
}
output

No comments:

Post a Comment