Insertion Sort for Doubly Linked List

22 Jun, 2022
Sort the doubly linked list using the insertion sort technique.
Initial doubly linked list 
Doubly Linked List after applying insertion sort 
Algorithm: Below is a simple insertion sort algorithm for doubly-linked lists.1) Create an empty sorted (or result) doubly linked list. 2) Traverse the given doubly linked list, and do the following for every node.      a) Insert the current node in a sorted way in the sorted(or result) doubly linked list. 3) Change the head of the given linked list to the head of the sorted (or result) list.The main step is (2. a), which has been covered in the post below. Sorted Insert for Doubly Linked List 
C++
Java
Python3
C#
Javascript
// C++ implementation for insertion Sort// on a doubly linked list#include <bits/stdc++.h> using namespace std; // Node of a doubly linked liststruct Node {    int data;    struct Node* prev, *next;}; // function to create and return a new node// of a doubly linked liststruct Node* getNode(int data){    // allocate node    struct Node* newNode =          (struct Node*)malloc(sizeof(struct Node));     // put in the data    newNode->data = data;    newNode->prev = newNode->next = NULL;    return newNode;} // function to insert a new node in sorted way in// a sorted doubly linked listvoid sortedInsert(struct Node** head_ref, struct Node* newNode){    struct Node* current;     // if list is empty    if (*head_ref == NULL)        *head_ref = newNode;     // if the node is to be inserted at the beginning    // of the doubly linked list    else if ((*head_ref)->data >= newNode->data) {        newNode->next = *head_ref;        newNode->next->prev = newNode;        *head_ref = newNode;    }     else {        current = *head_ref;         // locate the node after which the new node        // is to be inserted        while (current->next != NULL &&               current->next->data < newNode->data)            current = current->next;         /*Make the appropriate links */         newNode->next = current->next;         // if the new node is not inserted        // at the end of the list        if (current->next != NULL)            newNode->next->prev = newNode;         current->next = newNode;        newNode->prev = current;    }} // function to sort a doubly linked list using insertion sortvoid insertionSort(struct Node** head_ref){    // Initialize 'sorted' - a sorted doubly linked list    struct Node* sorted = NULL;     // Traverse the given doubly linked list and    // insert every node to 'sorted'    struct Node* current = *head_ref;    while (current != NULL) {         // Store next for next iteration        struct Node* next = current->next;         // removing all the links so as to create 'current'        // as a new node for insertion        current->prev = current->next = NULL;         // insert current in 'sorted' doubly linked list        sortedInsert(&sorted, current);         // Update current        current = next;    }     // Update head_ref to point to sorted doubly linked list    *head_ref = sorted;} // function to print the doubly linked listvoid printList(struct Node* head){    while (head != NULL) {        cout << head->data << " ";        head = head->next;    }} // function to insert a node at the beginning of// the doubly linked listvoid push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node =         (struct Node*)malloc(sizeof(struct Node));     /* put in the data  */    new_node->data = new_data;     /* Make next of new node as head and previous as NULL */    new_node->next = (*head_ref);    new_node->prev = NULL;     /* change prev of head node to new node */    if ((*head_ref) != NULL)        (*head_ref)->prev = new_node;     /* move the head to point to the new node */    (*head_ref) = new_node;} // Driver program to test aboveint main(){    /* start with the empty doubly linked list */    struct Node* head = NULL;     // insert the following data    push(&head, 9);    push(&head, 3);    push(&head, 5);    push(&head, 10);    push(&head, 12);    push(&head, 8);     cout << "Doubly Linked List Before Sortingn";    printList(head);     insertionSort(&head);     cout << "nDoubly Linked List After Sortingn";    printList(head);     return 0;}
// Java implementation for insertion Sort// on a doubly linked listclass Solution{ // Node of a doubly linked liststatic class Node{    int data;    Node prev, next;}; // function to create and return a new node// of a doubly linked liststatic Node getNode(int data){    // allocate node    Node newNode = new Node();     // put in the data    newNode.data = data;    newNode.prev = newNode.next = null;    return newNode;} // function to insert a new node in sorted way in// a sorted doubly linked liststatic Node sortedInsert(Node head_ref, Node newNode){    Node current;     // if list is empty    if (head_ref == null)        head_ref = newNode;     // if the node is to be inserted at the beginning    // of the doubly linked list    else if ((head_ref).data >= newNode.data)    {        newNode.next = head_ref;        newNode.next.prev = newNode;        head_ref = newNode;    }     else    {        current = head_ref;         // locate the node after which the new node        // is to be inserted        while (current.next != null &&            current.next.data < newNode.data)            current = current.next;         //Make the appropriate links /         newNode.next = current.next;         // if the new node is not inserted        // at the end of the list        if (current.next != null)            newNode.next.prev = newNode;         current.next = newNode;        newNode.prev = current;    }    return head_ref;} // function to sort a doubly linked list using insertion sortstatic Node insertionSort(Node head_ref){    // Initialize 'sorted' - a sorted doubly linked list    Node sorted = null;     // Traverse the given doubly linked list and    // insert every node to 'sorted'    Node current = head_ref;    while (current != null)    {         // Store next for next iteration        Node next = current.next;         // removing all the links so as to create 'current'        // as a new node for insertion        current.prev = current.next = null;         // insert current in 'sorted' doubly linked list        sorted=sortedInsert(sorted, current);         // Update current        current = next;    }     // Update head_ref to point to sorted doubly linked list    head_ref = sorted;         return head_ref;} // function to print the doubly linked liststatic void printList(Node head){    while (head != null)    {        System.out.print(head.data + " ");        head = head.next;    }} // function to insert a node at the beginning of// the doubly linked liststatic Node push(Node head_ref, int new_data){    // allocate node /    Node new_node = new Node();     // put in the data /    new_node.data = new_data;     // Make next of new node as head and previous as null /    new_node.next = (head_ref);    new_node.prev = null;     // change prev of head node to new node /    if ((head_ref) != null)        (head_ref).prev = new_node;     // move the head to point to the new node /    (head_ref) = new_node;         return head_ref;} // Driver codepublic static void main(String args[]){    // start with the empty doubly linked list /    Node head = null;     // insert the following data    head=push(head, 9);    head=push(head, 3);    head=push(head, 5);    head=push(head, 10);    head=push(head, 12);    head=push(head, 8);     System.out.println( "Doubly Linked List Before Sorting\n");    printList(head);     head=insertionSort(head);     System.out.println("\nDoubly Linked List After Sorting\n");    printList(head); }} // This code is contributed by Arnab Kundu
# Python3 implementation for insertion Sort# on a doubly linked list # Node of a doubly linked listclass Node:         def __init__(self, data):        self.data = data        self.prev = None        self.next = None # function to create and return a new node# of a doubly linked listdef getNode(data):     # allocate node    newNode = Node(0)     # put in the data    newNode.data = data    newNode.prev = newNode.next = None    return newNode # function to insert a new node in sorted way in# a sorted doubly linked listdef sortedInsert(head_ref, newNode):     current = None     # if list is empty    if (head_ref == None):        head_ref = newNode     # if the node is to be inserted at the beginning    # of the doubly linked list    elif ((head_ref).data >= newNode.data) :        newNode.next = head_ref        newNode.next.prev = newNode        head_ref = newNode         else :        current = head_ref         # locate the node after which the new node        # is to be inserted        while (current.next != None and            current.next.data < newNode.data):            current = current.next         """Make the appropriate links """        newNode.next = current.next         # if the new node is not inserted        # at the end of the list        if (current.next != None):            newNode.next.prev = newNode         current.next = newNode        newNode.prev = current         return head_ref;     # function to sort a doubly linked list# using insertion sortdef insertionSort( head_ref):     # Initialize 'sorted' - a sorted    # doubly linked list    sorted = None     # Traverse the given doubly linked list    # and insert every node to 'sorted'    current = head_ref    while (current != None) :         # Store next for next iteration        next = current.next         # removing all the links so as to create        # 'current' as a new node for insertion        current.prev = current.next = None         # insert current in 'sorted' doubly linked list        sorted = sortedInsert(sorted, current)         # Update current        current = next         # Update head_ref to point to    # sorted doubly linked list    head_ref = sorted         return head_ref # function to print the doubly linked listdef printList(head):     while (head != None) :        print( head.data, end = " ")        head = head.next     # function to insert a node at the# beginning of the doubly linked listdef push(head_ref, new_data):     """ allocate node """    new_node = Node(0)         """ put in the data """    new_node.data = new_data     """ Make next of new node as head    and previous as None """    new_node.next = (head_ref)    new_node.prev = None     """ change prev of head node to new node """    if ((head_ref) != None):        (head_ref).prev = new_node     """ move the head to point to the new node """    (head_ref) = new_node    return head_ref  # Driver Codeif __name__ == "__main__":     """ start with the empty doubly linked list """    head = None     # insert the following data    head = push(head, 9)    head = push(head, 3)    head = push(head, 5)    head = push(head, 10)    head = push(head, 12)    head = push(head, 8)     print( "Doubly Linked List Before Sorting")    printList(head)     head = insertionSort(head)     print("\nDoubly Linked List After Sorting")    printList(head) # This code is contributed by Arnab Kundu
// C# implementation for insertion Sort// on a doubly linked listusing System; class GFG{ // Node of a doubly linked listpublic class Node{    public int data;    public Node prev, next;}; // function to create and return a new node// of a doubly linked liststatic Node getNode(int data){    // allocate node    Node newNode = new Node();     // put in the data    newNode.data = data;    newNode.prev = newNode.next = null;    return newNode;} // function to insert a new node in sorted way// in a sorted doubly linked liststatic Node sortedInsert(Node head_ref,                         Node newNode){    Node current;     // if list is empty    if (head_ref == null)        head_ref = newNode;     // if the node is to be inserted at the beginning    // of the doubly linked list    else if ((head_ref).data >= newNode.data)    {        newNode.next = head_ref;        newNode.next.prev = newNode;        head_ref = newNode;    }     else    {        current = head_ref;         // locate the node after which        // the new node is to be inserted        while (current.next != null &&               current.next.data < newNode.data)            current = current.next;         //Make the appropriate links         newNode.next = current.next;         // if the new node is not inserted        // at the end of the list        if (current.next != null)            newNode.next.prev = newNode;         current.next = newNode;        newNode.prev = current;    }    return head_ref;} // function to sort a doubly linked list// using insertion sortstatic Node insertionSort(Node head_ref){    // Initialize 'sorted' - a sorted doubly linked list    Node sorted = null;     // Traverse the given doubly linked list and    // insert every node to 'sorted'    Node current = head_ref;    while (current != null)    {         // Store next for next iteration        Node next = current.next;         // removing all the links so as to create        // 'current' as a new node for insertion        current.prev = current.next = null;         // insert current in 'sorted' doubly linked list        sorted = sortedInsert(sorted, current);         // Update current        current = next;    }     // Update head_ref to point to    // sorted doubly linked list    head_ref = sorted;         return head_ref;} // function to print the doubly linked liststatic void printList(Node head){    while (head != null)    {        Console.Write(head.data + " ");        head = head.next;    }} // function to insert a node at the beginning of// the doubly linked liststatic Node push(Node head_ref, int new_data){    // allocate node    Node new_node = new Node();     // put in the data    new_node.data = new_data;     // Make next of new node as head    // and previous as null    new_node.next = (head_ref);    new_node.prev = null;     // change prev of head node to new node    if ((head_ref) != null)        (head_ref).prev = new_node;     // move the head to point to the new node    (head_ref) = new_node;         return head_ref;} // Driver codepublic static void Main(String []args){         // start with the empty doubly linked list    Node head = null;     // insert the following data    head = push(head, 9);    head = push(head, 3);    head = push(head, 5);    head = push(head, 10);    head = push(head, 12);    head = push(head, 8);     Console.WriteLine("Doubly Linked List Before Sorting");    printList(head);     head = insertionSort(head);     Console.WriteLine("\nDoubly Linked List After Sorting");    printList(head);}} // This code is contributed by Princi Singh
<script>    // javascript implementation for insertion Sort    // on a doubly linked list     // Node of a doubly linked list    class Node {        constructor(val) {            this.data = val;            this.prev = null;            this.next = null;        }    }    // function to create and return a new node    // of a doubly linked list    function getNode(data) {        // allocate node        var newNode = new Node();         // put in the data        newNode.data = data;        newNode.prev = newNode.next = null;        return newNode;    }     // function to insert a new node in sorted way in    // a sorted doubly linked list    function sortedInsert(head_ref,  newNode) {        var current;         // if list is empty        if (head_ref == null)            head_ref = newNode;         // if the node is to be inserted at the beginning        // of the doubly linked list        else if ((head_ref).data >= newNode.data) {            newNode.next = head_ref;            newNode.next.prev = newNode;            head_ref = newNode;        }         else {            current = head_ref;             // locate the node after which the new node            // is to be inserted            while (current.next != null && current.next.data < newNode.data)                current = current.next;             // Make the appropriate links /             newNode.next = current.next;             // if the new node is not inserted            // at the end of the list            if (current.next != null)                newNode.next.prev = newNode;             current.next = newNode;            newNode.prev = current;        }        return head_ref;    }     // function to sort a doubly linked list using insertion sort    function insertionSort(head_ref) {        // Initialize 'sorted' - a sorted doubly linked list        var sorted = null;         // Traverse the given doubly linked list and        // insert every node to 'sorted'        var current = head_ref;        while (current != null) {             // Store next for next iteration            var next = current.next;             // removing all the links so as to create 'current'            // as a new node for insertion            current.prev = current.next = null;             // insert current in 'sorted' doubly linked list            sorted = sortedInsert(sorted, current);             // Update current            current = next;        }         // Update head_ref to point to sorted doubly linked list        head_ref = sorted;         return head_ref;    }     // function to print the doubly linked list    function printList(head) {        while (head != null) {            document.write(head.data + " ");            head = head.next;        }    }     // function to insert a node at the beginning of    // the doubly linked list    function push(head_ref , new_data) {        // allocate node /        var new_node = new Node();         // put in the data /        new_node.data = new_data;         // Make next of new node as head and previous as null /        new_node.next = (head_ref);        new_node.prev = null;         // change prev of head node to new node /        if ((head_ref) != null)            (head_ref).prev = new_node;         // move the head to point to the new node /        (head_ref) = new_node;         return head_ref;    }     // Driver code         // start with the empty doubly linked list /    var head = null;     // insert the following data    head = push(head, 9);    head = push(head, 3);    head = push(head, 5);    head = push(head, 10);    head = push(head, 12);    head = push(head, 8);     document.write("Doubly Linked List Before Sorting<br/>");    printList(head);     head = insertionSort(head);     document.write("<br/>Doubly Linked List After Sorting<br/>");    printList(head);  // This code contributed by umadevi9616</script>
Output: 
Doubly Linked List Before Sorting
8 12 10 5 3 9
Doubly Linked List After Sorting
3 5 8 9 10 12
Time Complexity: O(n*n), as we are using a loop to traverse n times and in each traversal, we are calling the function sortedInsert which costs O(n) time (as we are traversing n time to insert the node). Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. 
andrew1234
princi singh
umadevi9616
simranarora5sos
rohan07
doubly linked list
Insertion Sort
Linked-List-Sorting
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HeapSort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Merge two sorted arrays
Count Inversions in an array | Set 1 (Using Merge Sort)
Sort an array of 0s, 1s and 2s | Dutch National Flag problem
Radix Sort
Chocolate Distribution Problem
Find a triplet that sum to a given value
k largest(or smallest) elements in an array