Open In App

Insertion Sort for Singly Linked List

Last Updated : 07 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm.

Examples:

Input: 5->4->1->3->2
Output: 1->2->3->4->5

Input: 4->3->2->1
Output: 1->2->3->4

The prerequisite is Insertion Sort on Array. The idea is to gradually build a sorted portion of the list within the same memory space as the original list.

Step-by-step approach:

  • Start with an initially empty “sorted” list, which will be built by rearranging nodes from the original list.
  • Traverse the original linked list one node at a time.
    • For each node, find its correct position within the “sorted” portion of the list.
    • If the node should be placed at the beginning (i.e., it’s smaller than the first node in the sorted list), it becomes the new head of the sorted list.
    • Otherwise, traverse the sorted list to find the correct position and insert the node there.
  • Continue this process until all nodes from the original list have been repositioned in the sorted order
  • Return the head of sorted list.

Below is the implementation of the above approach

C++
// C++ program to sort linked list
// using insertion sort
#include <bits/stdc++.h>
using namespace std;

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

// Function to insert a new_node in 
// the result list.
Node* sortedInsert(Node* newnode, Node* sorted) {
    
    // Special case for the head end
    if (sorted == NULL || 
        sorted->val >= newnode->val) {
        newnode->next = sorted;
        sorted = newnode;
    }
    else {
        Node* curr = sorted;
        
        // Locate the node before the point
      	// of insertion
        while (curr->next != NULL && 
               curr->next->val < newnode->val) {
            curr = curr->next;
        }
        newnode->next = curr->next;
        curr->next = newnode;
    }
    
    return sorted;
}

Node* insertionSort(Node* head) {
    
    // Initialize sorted linked list
    Node* sorted = NULL;
    Node* curr = head;
    
    // Traverse the given linked list and insert 
    // every node to sorted
    while (curr != NULL) {
        
        // Store next for next iteration
        Node* next = curr->next;
        
        // Insert current in sorted linked list
        sorted = sortedInsert(curr, sorted);
        
        // Update current
        curr = next;
    }
    
    return sorted;
}

void printList(Node* curr) {
    while (curr != NULL) {
        cout << " " << curr->val;
        curr = curr->next;
    }
}

int main() {
    
    // Create a hard-coded linked list:
    // 5->4->1->3->2
    Node* head = new Node(5);
    head->next = new Node(4);
    head->next->next = new Node(1);
    head->next->next->next = new Node(3);
    head->next->next->next->next = new Node(2);

    head = insertionSort(head);

    printList(head);

    return 0;
}
C
// C program to sort linked list using insertion sort
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int val;
    struct Node* next;
};

// Function to insert a new_node in the result list.
struct Node* sortedInsert(struct Node* createNode, 
                          struct Node* sorted) {
    
    // Special case for the head end
    if (sorted == NULL || 
        sorted->val >= createNode->val) {
        createNode->next = sorted;
        sorted = createNode;
    }
    else {
        struct Node* curr = sorted;
        
        // Locate the node before the point of insertion
        while (curr->next != NULL && 
               curr->next->val < createNode->val) {
            curr = curr->next;
        }
        createNode->next = curr->next;
        curr->next = createNode;
    }
    
    return sorted;
}

struct Node* insertionSort(struct Node* head) {
    
    // Initialize sorted linked list
    struct Node* sorted = NULL;
    struct Node* curr = head;
    
    // Traverse the given linked list and insert
    // every node to sorted
    while (curr != NULL) {
        
        // Store next for next iteration
        struct Node* next = curr->next;
        
        // Insert current in sorted linked list
        sorted = sortedInsert(curr, sorted);
        
        // Update current
        curr = next;
    }
    
    return sorted;
}

void printList(struct Node* curr) {
    while (curr != NULL) {
        printf(" %d", curr->val);
        curr = curr->next;
    }
}

struct Node* createNode(int x) {
    struct Node* node = 
     (struct Node*)malloc(sizeof(struct Node));
    node->val = x;
    node->next = NULL;
    return node;
}

int main() {
    
    // Create a hard-coded linked list:
    // 5->4->1->3->2
    struct Node* head = createNode(5);
    head->next = createNode(4);
    head->next->next = createNode(1);
    head->next->next->next = createNode(3);
    head->next->next->next->next = createNode(2);

    head = insertionSort(head);

    printList(head);

    return 0;
}
Java
// Java program to sort linked list
// using insertion sort

class Node {
    int val;
    Node next;

    Node(int x) {
        val = x;
        next = null;
    }
}

public class GfG {

    // Function to insert a new_node in
  	// the result list.
    static Node sortedInsert(Node newnode, 
                             Node sorted) {
        
        // Special case for the head end
        if (sorted == null || 
            sorted.val >= newnode.val) {
            newnode.next = sorted;
            sorted = newnode;
        } else {
            Node curr = sorted;
            
            // Locate the node before the 
          	// point of insertion
            while (curr.next != null && 
                   curr.next.val < newnode.val) {
                curr = curr.next;
            }
            newnode.next = curr.next;
            curr.next = newnode;
        }
        return sorted;
    }

    static Node insertionSort(Node head) {
        
        // Initialize sorted linked list
        Node sorted = null;
        Node curr = head;

        // Traverse the given linked list and 
      	// insert every node to sorted
        while (curr != null) {
            
            // Store next for next iteration
            Node next = curr.next;
            
            // Insert current in sorted linked list
            sorted = sortedInsert(curr, sorted);
            
            // Update current
            curr = next;
        }
        return sorted;
    }

    static void printList(Node curr) {
        while (curr != null) {
            System.out.print(" " + curr.val);
            curr = curr.next;
        }
    }

    public static void main(String[] args) {
        
        // Create a hard-coded linked list:
        // 5->4->1->3->2
        Node head = new Node(5);
        head.next = new Node(4);
        head.next.next = new Node(1);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(2);

        head = insertionSort(head);

        printList(head);
    }
}
Python
# Python program to sort linked list
# using insertion sort

class Node:
    def __init__(self, x):
        self.val = x
        self.next = None

def sorted_insert(newnode, sorted_head):
  
    # Special case for the head end
    if sorted_head is None or sorted_head.val >= newnode.val:
        newnode.next = sorted_head
        return newnode
    else:
        curr = sorted_head
        
        # Locate the node before the point of insertion
        while curr.next is not None and curr.next.val < newnode.val:
            curr = curr.next
        newnode.next = curr.next
        curr.next = newnode
        return sorted_head

def insertion_sort(head):
  
    # Initialize sorted linked list
    sorted_head = None
    curr = head
    
    # Traverse the given linked list and 
    # insert every node to sorted
    while curr is not None:
        next_node = curr.next
        
        # Insert current node in sorted linked list
        sorted_head = sorted_insert(curr, sorted_head)
        
        # Update current
        curr = next_node
    return sorted_head

def print_list(curr):
    while curr is not None:
        print(f" {curr.val}", end="")
        curr = curr.next
    print()

if __name__ == "__main__":
  
    # Create a hard-coded linked list:
    # 5->4->1->3->2
    head = Node(5)
    head.next = Node(4)
    head.next.next = Node(1)
    head.next.next.next = Node(3)
    head.next.next.next.next = Node(2)

    head = insertion_sort(head)

    print_list(head)
C#
// C# program to sort linked list
// using insertion sort

using System;

class Node {
    public int Val;
    public Node Next;

    public Node(int x) {
        Val = x;
        Next = null;
    }
}

class GfG {
    
    // Function to insert a new node in 
  	// the result list.
    static Node SortedInsert(Node newNode, 
                             Node sorted) {
        
        // Special case for the head end
        if (sorted == null || 
            sorted.Val >= newNode.Val) {
            newNode.Next = sorted;
            sorted = newNode;
        }
        else {
            Node curr = sorted;

            // Locate the node before the 
          	// point of insertion
            while (curr.Next != null && 
                   curr.Next.Val < newNode.Val) {
                curr = curr.Next;
            }
            newNode.Next = curr.Next;
            curr.Next = newNode;
        }

        return sorted;
    }

    static Node InsertionSort(Node head) {
      
        // Initialize sorted linked list
        Node sorted = null;
        Node curr = head;

        // Traverse the given linked list and 
      	// insert every node to sorted
        while (curr != null) {
            // Store next for next iteration
            Node next = curr.Next;

            // Insert current in sorted linked list
            sorted = SortedInsert(curr, sorted);

            // Update current
            curr = next;
        }

        return sorted;
    }

    static void PrintList(Node curr) {
        while (curr != null) {
            Console.Write(" " + curr.Val);
            curr = curr.Next;
        }
        Console.WriteLine();
    }

    static void Main() {
        
        // Create a hard-coded linked list:
        // 5->4->1->3->2
        Node head = new Node(5);
        head.Next = new Node(4);
        head.Next.Next = new Node(1);
        head.Next.Next.Next = new Node(3);
        head.Next.Next.Next.Next = new Node(2);
      
        head = InsertionSort(head);

        PrintList(head);
    }
}
JavaScript
// JavaScript program to sort linked list
// using insertion sort

class Node {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}

// Function to insert a new_node in 
// the result list.
function sortedInsert(newnode, sorted) {
    
    // Special case for the head end
    if (sorted === null || 
    sorted.val >= newnode.val) {
        newnode.next = sorted;
        sorted = newnode;
    } 
    else {
        let curr = sorted;

        // Locate the node before 
        // the point of insertion
        while (curr.next !== null && 
        curr.next.val < newnode.val) {
            curr = curr.next;
        }

        newnode.next = curr.next;
        curr.next = newnode;
    }

    return sorted;
}

function insertionSort(head) {
    
    // Initialize sorted linked list
    let sorted = null;
    let curr = head;

    // Traverse the given linked list 
    // and insert every node to sorted
    while (curr !== null) {
        
        // Store next for next iteration
        let next = curr.next;

        // Insert current in sorted linked list
        sorted = sortedInsert(curr, sorted);

        // Update current
        curr = next;
    }

    return sorted;
}

function printList(curr) {
    while (curr !== null) {
        console.log(" " + curr.val);
        curr = curr.next;
    }
    console.log();
}

// Create a hard-coded linked list:
// 5->4->1->3->2
let head = new Node(5);
head.next = new Node(4);
head.next.next = new Node(1);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(2);

head = insertionSort(head);

printList(head);

Output
 1 2 3 4 5

Time Complexity: O(n2), In the worst case, we might have to traverse all nodes of the sorted list for inserting a node.
Auxiliary Space: O(1), No extra space is required
 



Next Article
Article Tags :
Practice Tags :

Similar Reads