Insertion Sort for Doubly Linked List (original) (raw)

Last Updated : 17 Sep, 2024

Given a **doubly linked list, the task is to **sort the doubly linked list in **non-decreasing order using the **insertion sort.

**Examples:

**Input: head: 5<->3<->4<->1<->2
**Output: 1<->2<->3<->4<->5
**Explanation: Doubly Linked List after sorting using insertion sort technique is 1<->2<->3<->4<->5

**Input: head: 1<->5<->2<->3
**Output: 1<->2<->3<->5
**Explanation: Doubly Linked List after sorting using insertion sort technique is 1<->2<->3<->5

**Approach:

The insertion sort algorithm for a **doubly linked list works by repeatedly inserting nodes into a **sorted portion of the list. It starts with an empty sorted list and iterates through each node in the **unsorted part. For each node, it finds the **correct position in the sorted portion by comparing with nodes in the **sorted list. The node is then **inserted into its correct place, adjusting the pointers accordingly. This process continues until all nodes are placed in the sorted list.

Below is the implementation of the above approach:

C++ ``

// C++ program to sort a doubly linked list // using insertion sort #include using namespace std;

class Node { public: int data; Node* next; Node* prev;

Node(int x) {
    data = x;
    next = nullptr;
    prev = nullptr;
}

};

// Function to sort the doubly linked list // using insertion sort Node* insertionSort(Node* head) { if (head == nullptr) return head;

Node* sorted = nullptr;
Node* curr = head;

// Traverse the list to sort each element
while (curr != nullptr) {
  
    // Store the next node to process
    Node* next = curr->next;

    // Insert `curr` into the sorted part
    if (sorted == nullptr || 
                  sorted->data >= curr->data) {
        curr->next = sorted;

        // If sorted is not empty, set its `prev`
        if (sorted != nullptr) sorted->prev = curr;

        // Update sorted to the new head
        sorted = curr;
        sorted->prev = nullptr;

    } 
   else {
      
        // Pointer to traverse the sorted part
        Node* current_sorted = sorted;

        // Find the correct position to insert
        while (current_sorted->next != nullptr &&
               current_sorted->next->data < curr->data) {
            current_sorted = current_sorted->next;
        }

        // Insert `curr` after `current_sorted`
        curr->next = current_sorted->next;

        // Set `prev` if `curr` is not inserted 
        // at the end
        if (current_sorted->next != nullptr) 
            current_sorted->next->prev = curr;

        // Set `next` of `current_sorted` to `curr`
        current_sorted->next = curr;
        curr->prev = current_sorted;
    }

    // Move to the next node to be sorted
    curr = next;
}

return sorted;

}

void printList(Node* node) { Node* curr = node; while (curr != nullptr) { cout << " " << curr->data; curr = curr->next; } }

int main() {

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

head = insertionSort(head);

printList(head);

return 0;

}

C

// C program to sort a doubly linked list // using insertion sort #include <stdio.h> #include <stdlib.h>

struct Node { int data; struct Node* next; struct Node* prev; };

// Function to sort the doubly linked list using // insertion sort struct Node* insertionSort(struct Node* head) {

if (head == NULL) return head;
struct Node* sorted = NULL;
struct Node* curr = head;

// Traverse the list to sort each element
while (curr != NULL) {
  
    // Store the next node to process
    struct Node* next = curr->next;

    // Insert `curr` into the sorted part
    if (sorted == NULL || sorted->data >= curr->data) {
        curr->next = sorted;

        // If sorted is not empty, set its `prev`
        if (sorted != NULL) sorted->prev = curr;

        // Update sorted to the new head
        sorted = curr;
        sorted->prev = NULL;

    } 
    else {
      
        // Pointer to traverse the sorted part
        struct Node* current_sorted = sorted;

        // Find the correct position to insert
        while (current_sorted->next != NULL &&
               current_sorted->next->data < curr->data) {
            current_sorted = current_sorted->next;
        }

        // Insert `curr` after `current_sorted`
        curr->next = current_sorted->next;

        // Set `prev` if `curr` is not inserted
        // at the end
        if (current_sorted->next != NULL)
            current_sorted->next->prev = curr;

        // Set `next` of `current_sorted` to `curr`
        current_sorted->next = curr;
        curr->prev = current_sorted;
    }

    curr = next;
}

return sorted;

}

void printList(struct Node* node) {

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

}

struct Node* createNode(int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = NULL; new_node->prev = NULL; return new_node; }

int main() {

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

head = insertionSort(head);

printList(head);

return 0;

}

Java

// Java program to sort a doubly linked list // using insertion sort class Node { int data; Node next, prev;

Node(int x) {
    data = x;
    next = null;
    prev = null;
}

}

public class GfG {

// Function to sort the linked list using
// insertion sort
static Node insertionSort(Node head) {
    if (head == null) return head;

    // Sorted part of the list
    Node sorted = null;

    // Current node to be inserted
    Node curr = head;

    // Traverse the list to sort each element
    while (curr != null) {
      
        // Store the next node to process
        Node next = curr.next;

        // Insert `curr` into the sorted part
        if (sorted == null ||
                      sorted.data >= curr.data) {
            curr.next = sorted;

            // If sorted is not empty, set its `prev`
            if (sorted != null) sorted.prev = curr;

            // Update sorted to the new head
            sorted = curr;
            sorted.prev = null;

        } 
        else {
          
            // Pointer to traverse the sorted part
            Node currentSorted = sorted;

            // Find the correct position to insert
            while (currentSorted.next != null &&
                   currentSorted.next.data < curr.data) {
                currentSorted = currentSorted.next;
            }

            // Insert `curr` after `currentSorted`
            curr.next = currentSorted.next;

            // Set `prev` if `curr` is not inserted
            // at the end
            if (currentSorted.next != null)
                currentSorted.next.prev = curr;

            // Set `next` of `currentSorted` to `curr`
            currentSorted.next = curr;
            curr.prev = currentSorted;
        }
        curr = next;
    }

    return sorted;
}

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

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

    head = insertionSort(head);

    printList(head);
}

}

Python

Python program to sort a doubly linked list using

insertion sort

class Node: def init(self, data): self.data = data self.next = None self.prev = None

Function to sort the linked list using

insertion sort

def insertion_sort(head): if not head: return head

sorted_head = None
curr = head

# Traverse the list to sort each element
while curr:
  
    # Store the next node to process
    next_node = curr.next

    # Insert `curr` into the sorted part
    if not sorted_head or sorted_head.data >= curr.data:
        curr.next = sorted_head

        # If sorted is not empty, set its `prev`
        if sorted_head:
            sorted_head.prev = curr

        # Update sorted to the new head
        sorted_head = curr
        sorted_head.prev = None
    else:
      
        # Pointer to traverse the sorted part
        current_sorted = sorted_head

        # Find the correct position to insert
        while (current_sorted.next and
               current_sorted.next.data < curr.data):
            current_sorted = current_sorted.next

        # Insert `curr` after `current_sorted`
        curr.next = current_sorted.next

        # Set `prev` if `curr` is not inserted
        # at the end
        if current_sorted.next:
            current_sorted.next.prev = curr

        # Set `next` of `current_sorted` to `curr`
        current_sorted.next = curr
        curr.prev = current_sorted

    # Move to the next node to be sorted
    curr = next_node

return sorted_head

def print_list(node): curr = node while curr: print(curr.data, end=" ") curr = curr.next

if name == 'main':

# Create a hard-coded doubly linked list:
# 5 <-> 3 <-> 4 <-> 1 <-> 2
head = Node(5)
head.next = Node(3)
head.next.prev = head
head.next.next = Node(4)
head.next.next.prev = head.next
head.next.next.next = Node(1)
head.next.next.next.prev = head.next.next
head.next.next.next.next = Node(2)
head.next.next.next.next.prev = head.next.next.next

head = insertion_sort(head)
print_list(head)

C#

// C# program to sort a singly linked list using // insertion sort using System;

public class Node { public int data; public Node next;

public Node(int new_data) {
    data = new_data;
    next = null;
}

}

class GfG {

// Function to sort the linked list using
// insertion sort
static Node InsertionSort(Node head) {
    if (head == null) return head;

    Node sorted = null;
    Node curr = head;

    // Traverse the list to sort each element
    while (curr != null) {
      
        // Store the next node to process
        Node next = curr.next;

        // Insert `curr` into the sorted part
        if (sorted == null || sorted.data 
                                   >= curr.data) {
            curr.next = sorted;

            // Update sorted to the new head
            sorted = curr;
        } 
        else {
         
            // Pointer to traverse the sorted part
            Node currentSorted = sorted;

            // Find the correct position to insert
            while (currentSorted.next != null && 
                   currentSorted.next.data < curr.data) {
                currentSorted = currentSorted.next;
            }

            // Insert `curr` after `currentSorted`
            curr.next = currentSorted.next;
            currentSorted.next = curr;
        }
        curr = next;
    }

    return sorted;
}

static void PrintList(Node node) {
    Node curr = node;
    while (curr != null) {
        Console.Write(" " + curr.data);
        curr = curr.next;
    }
}

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

    head = InsertionSort(head);
    PrintList(head);
}

}

JavaScript

// JavaScript program to sort a doubly linked list // using insertion sort class Node { constructor(data) { this.data = data; this.next = null; this.prev = null; } }

// Function to sort the doubly linked list // using insertion sort function insertionSort(head) { if (!head) return head;

let sorted = null;
let curr = head;

// Traverse the list to sort each element
while (curr !== null) {

    // Store the next node to process
    let next = curr.next;

    // Insert `curr` into the sorted part
    if (sorted === null || sorted.data >= curr.data) {
        curr.next = sorted;

        // Update `prev` if sorted is not empty
        if (sorted !== null) sorted.prev = curr;

        // Update sorted to the new head
        sorted = curr;
        sorted.prev = null;
    } 
    else {
    
        // Pointer to traverse the sorted part
        let currentSorted = sorted;

        // Find the correct position to insert
        while (currentSorted.next !== null && 
               currentSorted.next.data < curr.data) {
            currentSorted = currentSorted.next;
        }

        // Insert `curr` after `currentSorted`
        curr.next = currentSorted.next;

        // Set `prev` if `curr` is not inserted at the end
        if (currentSorted.next !== null) 
            currentSorted.next.prev = curr;

        currentSorted.next = curr;
        curr.prev = currentSorted;
    }

    // Move to the next node to be sorted
    curr = next;
}

return sorted;

}

function printList(node) { let curr = node; while (curr !== null) { process.stdout.write(" " + curr.data); curr = curr.next; } }

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

head = insertionSort(head);

printList(head);

``

**Time Complexity: **O(n^2), as we are using nested loops for sorting, where **n is the number of nodes in the linked list.
**Auxiliary Space: O(1)

**Related article: