DEV Community

Navin S
Navin S

Posted on

๐Ÿ”— Merge Sort for Linked List (Step-by-Step Guide)

Sorting a linked list efficiently is an important problem in data structures.
Unlike arrays, linked lists do not support random access, so Merge Sort is the best choice.

๐Ÿ“Œ Problem Statement

Given the head of a linked list, sort it using Merge Sort and return the sorted list.

๐Ÿ” Examples

Example 1:
Input: 10 โ†’ 30 โ†’ 20 โ†’ 50 โ†’ 40 โ†’ 60
Output: 10 โ†’ 20 โ†’ 30 โ†’ 40 โ†’ 50 โ†’ 60

Example 2:
Input: 9 โ†’ 5 โ†’ 2 โ†’ 8
Output: 2 โ†’ 5 โ†’ 8 โ†’ 9

๐Ÿง  Intuition

Merge Sort works by:

Dividing the list into halves
Sorting each half recursively
Merging the sorted halves

๐Ÿ‘‰ This works efficiently for linked lists because merging is easy using pointers.

๐Ÿ”„ Approach (Merge Sort)

Step-by-Step:

Find the middle of the list
Split the list into two halves
Recursively sort both halves
Merge the sorted lists

๐Ÿ’ป Python Code

class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next

def get_middle(head):
slow = head
fast = head.next

while fast and fast.next:
    slow = slow.next
    fast = fast.next.next

return slow
Enter fullscreen mode Exit fullscreen mode

def merge(l1, l2):
dummy = ListNode()
tail = dummy

while l1 and l2:
    if l1.val <= l2.val:
        tail.next = l1
        l1 = l1.next
    else:
        tail.next = l2
        l2 = l2.next

    tail = tail.next

tail.next = l1 if l1 else l2
return dummy.next
Enter fullscreen mode Exit fullscreen mode

def merge_sort(head):
if not head or not head.next:
return head

# Step 1: find middle
mid = get_middle(head)
right_head = mid.next
mid.next = None

# Step 2: recursive sort
left = merge_sort(head)
right = merge_sort(right_head)

# Step 3: merge
return merge(left, right)
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Dry Run

For:
10 โ†’ 30 โ†’ 20 โ†’ 50

Step-by-step:

Split โ†’ [10 โ†’ 30] and [20 โ†’ 50]
Split further โ†’ [10], [30], [20], [50]
Merge โ†’ [10 โ†’ 30], [20 โ†’ 50]
Final merge โ†’ [10 โ†’ 20 โ†’ 30 โ†’ 50]

โšก Complexity

Time Complexity: O(n log n)
Space Complexity: O(log n) (recursion stack)

๐Ÿ”ฅ Why Merge Sort for Linked List?

No random access needed
Efficient merging using pointers
Better than QuickSort for linked lists

โš ๏ธ Edge Cases

Empty list
Single node
Already sorted list

๐Ÿ Conclusion

Merge Sort is the best algorithm for sorting linked lists because:

โœ” Efficient (O(n log n))
โœ” Stable sorting
โœ” Works well with pointer-based structures

Top comments (0)