  Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email  Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# Insertion Sort for Singly Linked List

Last Updated on April 20, 2023 by Prepbytes Insertion sort is a simple and efficient sorting algorithm that works well on small or nearly sorted data sets and it works similarly to the way you sort playing cards in your hands. The elements are virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed in the correct position in the sorted part. Insertion sort is also an ideal sorting algorithm for sorting the singly linked list. Let us study in detail the insertion sort in linked list and understand how the insertion sort using linked list works.

## Insertion Sort in Linked List

To perform the insertion sort using linked list, we will be given a singly linked list. We need to return the pointer to the head node after sorting the given linked list. Output after performing the insertion sort in linked list: Explanation: The given linked list is sorted and the sorted linked list is printed in the output.

This problem is not a tricky one. Let’s start performing insertion sort in linked list.

Let us take a brief look at the approach to perform the insertion sort using linked list.

### How to Perform Insertion Sort In Linked List?

The approach for performing insertion sort in linked list is going to be pretty simple.

• We will create an empty result singly linked list, which will be sorted.
• Then, we will traverse the given linked list, and for every node that we visit, we will insert the current node in a sorted way in our result list.
• To insert in a sorted way, follow these steps:
• We will traverse our result list and keep comparing every node with our current node.
• As soon as we find a node whose value is greater than the current node, we will insert the current node just before that node.
• If the current node value is greater than every other node of our result list, then we will append the current node at the end.
• After complete traversal, change the head of the given linked list to the head of the result list.

Let’s move to the algorithm to perform insertion sort using linked list to understand the approach in a more clear way

### Algorithm For Performing Insertion Sort Using Linked List

Here is the stepwise algorithm for performing the insertion sort in linked list.

• Step 1: Initialize the newly created sorted list as NULL.
• Step 2: Traverse the given singly linked list using a pointer say current.
• For every node, while traversal, store the next of node in a temp variable and remove all of its links.
• Insert the current node in a sorted way in the result list.
• Update the current value with a temp for further traversal.
• Step 3: Once the traversal is over, update the head pointer by making it point to our result list.
• Step 4: Return the head pointer.

### Dry Run For Performing Insertion Sort in Linked List

The dry run for the above-mentioned algorithm is given below.  ### Code Implementation For Performing Insertion Sort in Linked List

```#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node* next;
};

struct node* sorted = NULL;

void push(int val)
{
/* allocate node */
struct node* newnode
= (struct node*)malloc(sizeof(struct node));
newnode->data = val;
/* link the old list off the new node */
/* move the head to point to the new node */
}
void sortedInsert(struct node* newnode)
{
/* Special case for the head end */
if (sorted == NULL || sorted->data >= newnode->data) {
newnode->next = sorted;
sorted = newnode;
}
else {
struct node* current = sorted;
/* Locate the node before the point of insertion
*/
while (current->next != NULL
&& current->next->data < newnode->data) {
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}

// function to sort a singly linked list
// using insertion sort
void insertionsort()
{

// Traverse the given linked list and insert every
// node to sorted
while (current != NULL) {

// Store next for next iteration
struct node* next = current->next;

// insert current in sorted linked list
sortedInsert(current);

// Update current
current = next;
}
}

/* Function to print linked list */
{
}
printf("NULL");
}

// Driver program to test above functions
int main()
{

push(5);
push(20);
push(4);
push(3);
push(30);

printf("\n");

}
```
```#include <bits stdc++.h="">
using namespace std;

struct Node {
int val;
struct Node* next;
Node(int x)
{
val = x;
next = NULL;
}
};

public:

void push(int val)
{

Node* newnode = new Node(val);

}

{

while (current != NULL) {

Node* temp = current->next;

sortedInsert(current);
// Update current
current = temp;
}

}

void sortedInsert(Node* newnode)
{

}
else {

while (current->next != NULL
&& current->next->val < newnode->val) {
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}

{
cout << head->val << " ";
}
}
};
int main()
{

list.push(3);
list.push(1);
list.push(2);
list.push(4);
list.push(5);
cout << "Linked List before sorting" << endl;
cout << endl;
cout << "Sorted Linked List" << endl;
}
```
```public class LinkedlistIS
{

class node
{
int val;
node next;

public node(int val)
{
this.val = val;
}
}

void push(int val)
{

node newnode = new node(val);

}

{

while (current != null)
{

node temp = current.next;

sortedInsert(current);

current = temp;
}

}

void sortedInsert(node newnode)
{

{
}
else
{

while (current.next != null && current.next.val < newnode.val)
{
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}

{
{
}
}

public static void main(String[] args)
{

list.push(3);
list.push(1);
list.push(2);
list.push(4);
list.push(5);
}
}
```
```class Node:

def __init__(self, data):
self.data = data
self.next = None

sorted = None
while (current != None):

next = current.next
sorted = sortedInsert(sorted, current)
current = next

current = None

else:

while (current.next != None and
current.next.data < new_node.data):

current = current.next

new_node.next = current.next
current.next = new_node

while(temp != None):

print( temp.data, end = " ")
temp = temp.next

new_node = Node(0)
new_node.data = new_data

a = None
a = push(a, 3)
a = push(a, 1)
a = push(a, 2)
a = push(a, 4)
a = push(a, 5)

printList(a)

a = insertionSort(a)

printList(a)
```

Output

``````Linked List before Sorting.
5 4 2 1 3
1 2 3 4 5``````

Time Complexity For Performing Insertion Sort using Linked List: O(n2), as we are using nested traversal

Space Complexity For Performing Insertion Sort using Linked List: O(1), as no extra is required depending on the size of the input.

Here are some Frequently Asked Questions related to insertion sort in linked list.

Ques 1. What is insertion sort?
Ans. Insertion sort is a simple sorting algorithm that works by dividing the input into two sections: a sorted section and an unsorted section. Initially, the sorted section is empty, and the unsorted section contains all the elements in the input. The algorithm then iterates through the unsorted section, comparing each element with the elements in the sorted section and inserting it in the correct position.

Ques 2. Why insertion is faster in the LinkedList in comparison to ArrayList?
Ans. A LinkedList consumes a bit more memory than an ArrayList since every node stores two references to the previous and next elements. The insertion, addition, and removal operations are faster in a LinkedList because there is no resizing of an array done in the background.

Ques 3. What happens if the linked list is empty during insertion sort?
Ans. If the linked list is empty during insertion sort, the algorithm simply returns the empty list.

Ques 4. Is insertion sort in linked list stable?
Ans. Yes, insertion sort in linked list is stable, meaning that the order of equal elements in the original list will be preserved after sorting.