Merge Sort for Linked List

Merge Sort for Linked List

01 Sep 2025
Beginner
30 Views
4 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

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.

GET FREE CHALLENGE

Share Article
About Author
Amit Kumar Ghosh (SDE and Mentor at Scholarhat)

As a software developer with a wealth of experience, he brings a unique combination of technical acumen and a passion for mentorship to my role. With 6 years of experience, he has honed the skills in C/C++, Java, Python, SQL, C#, JavaScript, React, Java Spring etc. and has a proven track record of delivering high-quality, scalable software solutions and core Computer fundamental knowledge DSA, OOPs, CN, OS etc.

As a teacher, his approach revolves around interactive techniques, prioritizing hands-on learning and real-world projects. He explains concepts clearly, offer practical examples, and encourage questions to foster a supportive environment.
Live Training - Book Free Demo
ASP.NET Core Certification Training
06 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Advanced Full-Stack .NET Developer with Gen AI Certification Training
06 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Azure AI Foundry Certification Training
06 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
React Certification Training
07 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Azure Developer Certification Training
08 Sep
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this