700132. QuickSort on Doubly Linked List
Here is the detailed Markdown blog post for the GeeksforGeeks problem:
Quicksort on Doubly Linked List
Summary
The task is to implement the Quicksort algorithm on a doubly linked list. The Quicksort algorithm is a popular sorting technique that works by selecting a pivot element, partitioning the list around it, and then recursively applying the same process to the sublists. This problem requires us to adapt this algorithm for use with a doubly linked list, which has its own set of complexities due to the added pointers.
Detailed Explanation
To sort a doubly linked list using Quicksort, we first need to select a pivot element. We can do this by choosing any node in the list and partitioning the rest of the nodes around it. The key difference between sorting an array or singly-linked list and a doubly-linked list is that we have to handle the pointers correctly.
Here's a step-by-step breakdown of the solution:
- Select a pivot element from the list.
- Partition the list around the pivot, such that all nodes less than the pivot come before it in the sorted list, and all nodes greater than the pivot come after it.
- Recursively apply steps 1-2 to the sublists of nodes less than and greater than the pivot until the entire list is sorted.
Here's an ASCII art diagram illustrating the partitioning step:
+-----------+ +-----------+
| 3 |----| 5 | | 1 |----| 2 |
+-----------+ +-----------+
^ ^
| |
v v
+-----------+ +-----------+
| 8 |----| 9 | | 4 |----| 6 |
+-----------+ +-----------+
In this diagram, the pivot element (5) is shown in the middle. The nodes less than the pivot (1, 2, and 3) are on the left, while the nodes greater than the pivot (8, 9) are on the right.
Time complexity: O(n log n) Space complexity: O(log n)
Optimized Solutions
Here are optimized solutions in various languages:
Java
java
public class QuickSortOnDoublyLinkedList {
public static void quickSort(Node head) {
if (head == null || head.next == null) return;
Node pivot = partition(head);
quickSort(pivot.prev);
while (pivot != head.next) {
pivot = pivot.next;
}
quickSort(pivot.next);
}
private static Node partition(Node head) {
Node pivot = head;
Node prev = null;
Node next = null;
while (head != null) {
if (head.data < pivot.data) {
prev = head;
head = head.next;
} else if (head.data > pivot.data) {
next = head;
head = head.next;
} else {
head = head.next;
}
}
Node temp = pivot.prev;
pivot.prev = prev;
prev.next = pivot;
pivot.next = next;
next.prev = pivot;
return next;
}
}
Python
Not available