Saturday 14 September 2013

Saturday 14 September 2013

Sorting elements in Linkedlist


 C program to sort  elements in Linkedlist

//we are going to sort the elements in the linkedlist using selection sort having efficiency O(n).
#include <stdio.h>
#include <stdlib.h>

struct node{
    struct node *link;
    int data;
    };
  
    void insert(struct node **,int);
    void display(struct node *);
    int count(struct node *);
    void sort(struct node *);
   
    int main(){
        struct node *s;
        s=NULL;
        insert(&s,70);
        insert(&s,20);
        insert(&s,40);
        insert(&s,50);

        display(s);
        sort(s);
        display(s);
      
        count(s);
        return 0;
    }
  
    void insert(struct node **s,int num){
        struct node *temp;
        temp=(struct node*)malloc(sizeof(struct node));
        temp->data=num;
        temp->link=*s;
        *s=temp;
    }
    void display(struct node *s){
   
        while(s!=NULL){
            printf("%d \n",s->data);
            s=s->link;
        }
        printf("\n");
    }

int count(struct node *s){
        int i;
        i=0;
        while(s!=NULL){
          
            s=s->link;
            i++;
        }
        printf("%d",i);
    }
//Selection sort 
void sort(struct node *s){
   struct node *p,*q;
   int temp;
   p=s;
   while(p!=NULL){
       q=p->link;
       while(q!=NULL){
           if(p->data < q->data){
               temp=p->data;
               p->data=q->data;
               q->data=temp;
               
           }
           q=q->link;
           
       }p=p->link;
   }
   }
 Executing the program....
$demo
50 
40 
20 
70 
After sort
70 
50 
40 
20 

4
  

No comments:

Post a Comment