05
SepMerge Sort for Linked List
Merge Sort for Linked List
The Merge Sort Algorithm for a linked list is a divide-and-conquer sorting algorithm that recursively divides the linked list into two halves, sorts each half, and then merges the sorted halves. Unlike arrays, linked lists are ideal for merge sort because they don’t require random access, and the merge operation can be performed efficiently in O(n log n) time, where n is the number of nodes. This algorithm is stable and particularly effective for linked lists due to their sequential access nature.
Example
- Input: Linked List = 4 -> 2 -> 1 -> 3
- Output: 1 -> 2 -> 3 -> 4
- Explanation: The linked list is sorted in ascending order.
Logic
Enter a list of numbers (comma-separated) to create a linked list and sort it using the Merge Sort algorithm.
Program (Python - Merge Sort for Linked List)
The following Python code implements the Merge Sort algorithm for a singly linked list with O(n log n) time complexity and O(log n) space complexity for the recursive call stack.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeSort(head):
# Base case: if list is empty or has one node
if not head or not head.next:
return head
# Find the middle of the list using slow and fast pointers
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
second_half = slow.next
slow.next = None
# Recursively sort the two halves
left = mergeSort(head)
right = mergeSort(second_half)
# Merge the sorted halves
return merge(left, right)
def merge(left, right):
dummy = ListNode(0)
current = dummy
# Merge two sorted lists
while left and right:
if left.val <= right.val:
current.next = left
left = left.next
else:
current.next = right
right = right.next
current = current.next
# Append remaining nodes
current.next = left if left else right
return dummy.next
# Helper function to create linked list from array
def createLinkedList(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to convert linked list to array for printing
def linkedListToArray(head):
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result
# Example usage
arr = [4, 2, 1, 3]
head = createLinkedList(arr)
sorted_head = mergeSort(head)
print(linkedListToArray(sorted_head)) # Output: [1, 2, 3, 4]
Output
For the input linked list created from [4, 2, 1, 3], the output is:
[1, 2, 3, 4]
Explanation:
The linked list is sorted in ascending order using the merge sort algorithm.
Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.