Given a doubly linked list containing n nodes, where each node is at most k away from its target position in the list. The problem is to sort the given doubly linked list.
For example, let us consider k is 2, a node at position 7 in the sorted doubly linked list, can be at positions 5, 6, 7, 8, 9 in the given doubly linked list.
Naive Approach: Sort the given doubly linked list using insertion sort technique.
Time Complexity: O(nk)
Auxiliary Space: O(1)
Efficient Approach: We can sort the list using the MIN HEAP data structure. The approach has been explained in Sort a nearly sorted (or K sorted) array. We only have to be careful while traversing the input doubly linked list and adjusting the required next and previous links in the final sorted list.
Original Doubly linked list: 3 6 2 12 56 8 Doubly linked list after sorting: 2 3 6 8 12 56
Time Complexity: O(nLogk)
Auxiliary Space: O(k)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Merge K sorted Doubly Linked List in Sorted Order
- Insert value in sorted way in a sorted doubly linked list
- Remove duplicates from a sorted doubly linked list
- Insertion Sort for Doubly Linked List
- Merge Sort for Doubly Linked List
- Sort the biotonic doubly linked list | Set-2
- Sort the biotonic doubly linked list
- Bubble Sort On Doubly Linked List
- Find pairs with given product in a sorted Doubly Linked List
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Count triplets in a sorted doubly linked list whose product is equal to a given value x
- Sorted insert in a doubly linked list with head and tail pointers
- Sort linked list which is already sorted on absolute values
- Sort a linked list that is sorted alternating ascending and descending orders?
- Sorted merge of two sorted doubly circular linked lists