Thursday, 28 May 2015

Sorting of nodes in Linked list(Selection sort)


// Linked list sorting using selection sort
#include<stdio.h>
#include<stdlib.h>
struct type
{
   int data;
   struct type *link;
};
typedef struct type *node;
main()
{
   node q,p,temp,header,ptr,car;
   int size,i,wer;
   printf("enter how many nodes\n");
   scanf("%d",&size);
   for(i=0;i<size;i++)
    {
       temp=(node )malloc(sizeof(node));
       printf("\n enter value %d: ",i+1);
       scanf("%d",&temp->data);
       if(!i)
       ptr=temp;
       else
        {
           car->link=temp;
            temp->link=NULL;
        }
           car=temp;
    }
    temp=ptr;
    printf("\n the details entered are \n");
    while(temp!=NULL)
    {
       printf("%d\t",temp->data);
       temp=temp->link;
    }
    q=ptr;
    while(q!=NULL)
    {
       p=q->link;
       while(p!=NULL)
       {
           if(q->data>p->data)
             {
               wer=q->data;
               q->data=p->data;
               p->data=wer;
             }
             p=p->link;
       }
       q=q->link;
    }
    printf("\nafter sorting details are:\n");
    q=ptr;
    while(q!=NULL)
    {
       printf("%d\t",q->data);
       q=q->link;
    }
    
}



No comments:

Post a Comment