Skip to content
Related Articles

Related Articles

Java Program for Merge Sort for Linked Lists
  • Difficulty Level : Hard
  • Last Updated : 02 Jan, 2019

Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.
sorting image

Let head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so head node has to be changed if the data at original head is not the smallest value in linked list.

1) If head is NULL or there is only one element in the Linked List 
    then return.
2) Else divide the linked list into two halves.  
      FrontBackSplit(head, &a, &b); /* a and b are two halves */
3) Sort the two halves a and b.
4) Merge the sorted a and b (using SortedMerge() discussed here) 
   and update the head pointer using headRef.
     *headRef = SortedMerge(a, b);

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.


// Java program to illustrate merge sorted
// of linkedList
public class linkedList {
    node head = null;
    // node a, b;
    static class node {
        int val;
        node next;
        public node(int val)
            this.val = val;
    node sortedMerge(node a, node b)
        node result = null;
        /* Base cases */
        if (a == null)
            return b;
        if (b == null)
            return a;
        /* Pick either a or b, and recur */
        if (a.val <= b.val) {
            result = a;
   = sortedMerge(, b);
        else {
            result = b;
   = sortedMerge(a,;
        return result;
    node mergeSort(node h)
        // Base case : if head is null
        if (h == null || == null) {
            return h;
        // get the middle of the list
        node middle = getMiddle(h);
        node nextofmiddle =;
        // set the next of middle node to null = null;
        // Apply mergeSort on left list
        node left = mergeSort(h);
        // Apply mergeSort on right list
        node right = mergeSort(nextofmiddle);
        // Merge the left and right lists
        node sortedlist = sortedMerge(left, right);
        return sortedlist;
    // Utility function to get the middle of the linked list
    node getMiddle(node h)
        // Base case
        if (h == null)
            return h;
        node fastptr =;
        node slowptr = h;
        // Move fastptr by two and slow ptr by one
        // Finally slowptr will point to middle node
        while (fastptr != null) {
            fastptr =;
            if (fastptr != null) {
                slowptr =;
                fastptr =;
        return slowptr;
    void push(int new_data)
        /* allocate node */
        node new_node = new node(new_data);
        /* link the old list off the new node */ = head;
        /* move the head to point to the new node */
        head = new_node;
    // Utility function to print the linked list
    void printList(node headref)
        while (headref != null) {
            System.out.print(headref.val + " ");
            headref =;
    public static void main(String[] args)
        linkedList li = new linkedList();
         * Let us create a unsorted linked lists to test the functions Created
         * lists shall be a: 2->3->20->5->10->15
        System.out.println("Linked List without sorting is :");
        // Apply merge Sort
        li.head = li.mergeSort(li.head);
        System.out.print("\n Sorted Linked List is: \n");
// This code is contributed by Rishabh Mahrsee
Linked List without sorting is :
2 3 20 5 10 15 
 Sorted Linked List is: 
2 3 5 10 15 20

Please refer complete article on Merge Sort for Linked Lists for more details!

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :