VOOZH about

URL: https://www.geeksforgeeks.org/dsa/insertion-sort-doubly-linked-list/

⇱ Insertion Sort for Doubly Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


Output
 1 2 3 4 5

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:

Comment