This post is completed by 1 user
|
Add to List |
102. Merge Sort for Linked Lists (In-place Algorithm)
Objective: Given a Linked List, Sort it using merge sort.
Example:
->9->3->4->2->5->1 Sorted List: ->1->2->3->4->5->9
Approach:
the process involves dividing the list into smaller segments, sorting each segment individually, and then merging them back together in a sorted manner. Here's the description rewritten:
To implement Merge Sort on a linked list, we follow the Divide and Conquer approach:
- Determine the length of the linked list, denoted as L.
- Calculate the midpoint of the list, L/2.
- Divide the list into two equal parts.
- Move a pointer (oldHead) to the middle of the list by traversing L/2 nodes.
- Create a new pointer (newHead) and set it to oldHead.next.
- Set oldHead.next to null, effectively splitting the list into two parts.
- Reset oldHead to the beginning of the original list.
- At this stage, the list is divided into two parts, with oldHead and newHead pointing to the start of each segment.
- Recursively apply Merge Sort to these two segments.
- Merge the sorted segments back together into a single sorted list.
- Click here to read How to merge two sorted Linked Lists
Output:
->9->3->4->2->5->1 Sorted List: ->1->2->3->4->5->9
Reference: Merge Sort in array