Sorting of Linked List in Increasing Order


Today we will be discussing how to sorting of linked list in increasing order. But if you are unfamiliar with linked list then refer to this link where I have explained you about linked list from basic to advance. Suppose we have a linked list 4->2->5->8->1 then after sorting it should look like 1->2->4->5->8. So, let's discuss the procedure to solve the problem.

Procedure


 1. First we will make a linked list.
2. Now we have many sorting algorithms like bubble sort, insertion sort, selection sort etc. We will be using bubble sort for sorting our list.
3. Now I hope you guys know how bubble sort works in arrays. If you do not know then refer to this link .
4. We will use bubble to sort linked list in the similar way we use it to sort an array.


Code



Explanation of Code 


1. First we will write a simple code of linked list which will have 2 functions:
     - insert() - which will insert elements in the linked list.
     - disp() - which will display the linked list.
2. Insert some values in the linked list.
3. Now we have created a function named sort() for sorting of linked list in increasing order.
4. Then we have created 'temp' which is a pointer to node. It is initialized to head .
5.  Now we have started a while loop for iterating the list. Remember we are iterating from first node till the second last node.
     while(temp->next!=NULL)
6. Then we have created a new 'temp1' which is another pointer to node. It is initialized to temp->next which means it will always point to the next node of temp .
    struct node* temp1=temp->next;
7. Now we are starting another loop from temp1 till the last node.
    while(temp1!=NULL)

SEE ALSO : 
The Ultimate Guide To Best Sorting Algorithms With Programs


Sorting of Linked List in Increasing Order


8. Then we are comparing the data of 2 nodes adjacent to each other. If data of previous node is greater than the data of node ahead of it the  we will swap the 2 nodes.
    if(temp->data > temp1->data)
   {
        swap(temp->data,temp1->data);
   }

9. Then we have incremented temp1 so that it can point to a new node.
   temp1=temp1->next;
10. This loop will run until a node comes to its original position in a sorted list.
11. Then outside this loop we have incremented temp.
    temp=temp->next;


If you guys want me to sort linked list using some other sorting algorithm then please comment below.

2 Comments

  1. swap function not defined

    ReplyDelete
    Replies
    1. And instead of passing data in swap pass the pointer address

      Delete
Post a Comment
Previous Post Next Post