Insertion Sort for Doubly Linked List
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 <iostream>
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:
Similar Reads
Insertion in a Doubly Linked List Inserting a new node in a doubly linked list is very similar to inserting new node in linked list. There is a little extra work required to maintain the link of the previous node. In this article, we will learn about different ways to insert a node in a doubly linked list.Table of ContentInsertion a
6 min read
Insertion Sort for Singly Linked List 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->2Output: 1->2->3->4->5Input: 4->3->2->1Output: 1->2->3->4The prerequisite is Insertion Sort on Array. The idea is to
8 min read
Sorted insert for circular linked list Given a sorted circular linked list, your task is to insert a new node in this circular list so that it remains a sorted circular linked list.Examples:Input: head = 1Â â2Â â4, data = 2Output: 1Â â2Â â2Â â4Explanation: We can add 2 after the second node.Input: head = 1Â â4Â â7Â â9, data = 5Output: 1Â â4Â â5Â â7
10 min read
Insertion in Doubly Circular Linked List Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two consecutive elements are linked or connected by the previous and next pointer and the last node points to the first node by the next pointer and also the first node points to the last node by
15+ min read
Insertion in Linked List Insertion in a linked list involves adding a new node at a specified position in the list. There are several types of insertion based on the position where the new node is to be added:At the front of the linked list Before a given node.After a given node.At a specific position.At the end of the link
4 min read
Introduction to Doubly Linked Lists in Java Doubly linked list is a data structure that has reference to both the previous and next nodes in the list. It provides simplicity to traverse, insert and delete the nodes in both directions in a list. In a doubly linked list, each node contains three data members: data: The data stored in the nodene
11 min read
Memory efficient doubly linked list We need to implement a doubly linked list with the use of a single pointer in each node. For that we are given a stream of data of size n for the linked list, your task is to make the function insert() and getList(). The insert() function pushes (or inserts at the beginning) the given data in the li
9 min read
Doubly Linked List in Python Doubly Linked List is a type of linked list in which each node contains a data element and two links pointing to the next and previous node in the sequence. This allows for more efficient operations such as traversals, insertions, and deletions because it can be done in both directions. Table of Con
13 min read
Insert a Node at the end of Doubly Linked List Given a Doubly Linked List, the task is to insert a new node at the end of the linked list.Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4Input: Linked List = NULL, NewNode = 1Output: Linked List = 1Approach: Inserting
9 min read
Insertion in Circular Singly Linked List In this article, we will learn how to insert a node into a circular linked list. Insertion is a fundamental operation in linked lists that involves adding a new node to the list. In a circular linked list, the last node connects back to the first node, creating a loop.There are four main ways to add
12 min read