We have discussed Insertion Sort for arrays. In this article we discuss about linked list.
Singly Linked List:
Singly Linked List is a collection of ordered set of elements. A Node in singly linked list has two parts – data part and link part. Data part of the node contains the actual information which is represented as node. Link part of the node contains address of next node linked to it.
It can be traversed in only one direction because the node stores only next pointer. So, it can’t reverse linked list.

Algorithm for Insertion Sort for Singly Linked List :
- Create an empty sorted (or result) list
- Traverse the given list, do following for every node.
- Insert current node in sorted way in sorted or result list.
- Change head of given linked list to head of sorted (or result) list.
Insertion Sort for Singly Linked List:
In C language, program is given below:
c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void sortedInsert(struct node**, struct node*);
void insertionSort(struct node **head_ref)
{
struct node *sorted = NULL;
struct node *current = *head_ref;
while (current != NULL)
{
struct node *next = current->next;
sortedInsert(&sorted, current);
current = next;
}
*head_ref = sorted;
}
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current;
if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
current = *head_ref;
while (current->next!=NULL &&
current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
void push(struct node** head_ref, int new_data)
{
struct node* new_node = new node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main()
{
struct node *a = NULL;
push(&a, 5);
push(&a, 20);
push(&a, 4);
push(&a, 3);
push(&a, 30);
printf("Linked List before sorting \n");
printList(a);
insertionSort(&a);
printf("\nLinked List after sorting \n");
printList(a);
return 0;
}
OUTPUT:
Linked List before sorting
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
[ad type=”banner”]