Open In App

C++ Program For Merge Sort Of Linked Lists

Improve
Improve
Like Article
Like
Save
Share
Report

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 the 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 the head node has to be changed if the data at the original head is not the smallest value in the linked list. 

MergeSort(headRef)
1) If the 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.
      MergeSort(a);
      MergeSort(b);
4) Merge the sorted a and b (using SortedMerge() discussed here) 
   and update the head pointer using headRef.
     *headRef = SortedMerge(a, b);
 

C++




// C++ code for linked list merged sort
#include <bits/stdc++.h>
using namespace std;
  
// Link list node 
class Node 
{
    public:
    int data;
    Node* next;
};
  
// Function prototypes 
Node* SortedMerge(Node* a, 
                  Node* b);
void FrontBackSplit(Node* source,
                    Node** frontRef, 
                    Node** backRef);
  
// Sorts the linked list by changing 
// next pointers (not data) 
void MergeSort(Node** headRef)
{
    Node* head = *headRef;
    Node* a;
    Node* b;
  
    // Base case -- length 0 or 1 
    if ((head == NULL) || 
        (head->next == NULL)) 
    {
        return;
    }
  
    /* Split head into 'a' and 'b' 
       sublists */
    FrontBackSplit(head, &a, &b);
  
    // Recursively sort the sublists 
    MergeSort(&a);
    MergeSort(&b);
  
    /* answer = merge the two sorted 
       lists together */
    *headRef = SortedMerge(a, b);
}
  
/* See https:// www.geeksforgeeks.org/?p=3622 
   for details of this function */
Node* SortedMerge(Node* a, Node* b)
{
    Node* result = NULL;
  
    // Base cases 
    if (a == NULL)
        return (b);
    else if (b == NULL)
        return (a);
  
    /* Pick either a or b, and 
       recur */
    if (a->data <= b->data) 
    {
        result = a;
        result->next = 
                SortedMerge(a->next, b);
    }
    else 
    {
        result = b;
        result->next = 
                SortedMerge(a, b->next);
    }
    return (result);
}
  
// UTILITY FUNCTIONS 
/* Split the nodes of the given list into 
   front and back halves, and return the two 
   lists using the reference parameters. If 
   the length is odd, the extra node should 
   go in the front list. Uses the fast/slow 
   pointer strategy. */
void FrontBackSplit(Node* source,
                    Node** frontRef, 
                    Node** backRef)
{
    Node* fast;
    Node* slow;
    slow = source;
    fast = source->next;
  
    /* Advance 'fast' two nodes, and 
       advance 'slow' one node */
    while (fast != NULL) 
    {
        fast = fast->next;
        if (fast != NULL) 
        {
            slow = slow->next;
            fast = fast->next;
        }
    }
  
    /* 'slow' is before the midpoint in 
        the list, so split it in two at 
        that point. */
    *frontRef = source;
    *backRef = slow->next;
    slow->next = NULL;
}
  
/* Function to print nodes in a 
   given linked list */
void printList(Node* node)
{
    while (node != NULL) 
    {
        cout << node->data << " ";
        node = node->next;
    }
}
  
/* Function to insert a node at the 
   beginning of the linked list */
void push(Node** head_ref, int new_data)
{
    // Allocate node 
    Node* new_node = new Node();
  
    // Put in the data 
    new_node->data = new_data;
  
    // Link the old list off the 
    // new node 
    new_node->next = (*head_ref);
  
    // Move the head to point to 
    // the new node 
    (*head_ref) = new_node;
}
  
// Driver code
int main()
{
    // Start with the empty list 
    Node* res = NULL;
    Node* a = NULL;
  
    /* Let us create a unsorted linked lists 
       to test the functions created lists shall 
       be a: 2->3->20->5->10->15 */
    push(&a, 15);
    push(&a, 10);
    push(&a, 5);
    push(&a, 20);
    push(&a, 3);
    push(&a, 2);
  
    // Sort the above created Linked List 
    MergeSort(&a);
  
    cout << "Sorted Linked List is: ";
    printList(a);
  
    return 0;
}
// This is code is contributed by rathbhupendra


Output:

Sorted Linked List is: 
2 3 5 10 15 20

Time Complexity: O(n*log n)

Space Complexity: O(n*log n)

Approach 2: This approach is simpler and uses log n space.

mergeSort():

  1. If the size of the linked list is 1 then return the head
  2. Find mid using The Tortoise and The Hare Approach
  3. Store the next of mid in head2 i.e. the right sub-linked list.
  4. Now Make the next midpoint null.
  5. Recursively call mergeSort() on both left and right sub-linked list and store the new head of the left and right linked list.
  6. Call merge() given the arguments new heads of left and right sub-linked lists and store the final head returned after merging.
  7. Return the final head of the merged linkedlist.

merge(head1, head2):

  1. Take a pointer say merged to store the merged list in it and store a dummy node in it.
  2. Take a pointer temp and assign merge to it.
  3. If the data of head1 is less than the data of head2, then, store head1 in next of temp & move head1 to the next of head1.
  4. Else store head2 in next of temp & move head2 to the next of head2.
  5. Move temp to the next of temp.
  6. Repeat steps 3, 4 & 5 until head1 is not equal to null and head2 is not equal to null.
  7. Now add any remaining nodes of the first or the second linked list to the merged linked list.
  8. Return the next of merged(that will ignore the dummy and return the head of the final merged linked list)

C++




// C++ program to implement
// the above approach
#include<iostream>
using namespace std;
  
// Node structure
struct Node
{
    int data;
    Node *next;
};
  
// Function to insert in list
void insert(int x, Node **head) 
{
    if(*head == NULL)
    {
        *head = new Node;
        (*head)->data = x;
        (*head)->next = NULL;
        return;
    }
  
    Node *temp = new Node;
    temp->data = (*head)->data;
    temp->next = (*head)->next;
    (*head)->data = x;
    (*head)->next = temp;
}
  
// Function to print the list
void print(Node *head) 
{
    Node *temp = head;
    while(temp != NULL) 
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
}
  
Node *merge(Node *firstNode,
            Node *secondNode) 
{
    Node *merged = new Node;
    Node *temp = new Node;
     
    // Merged is equal to temp so in the 
    // end we have the top Node.
    merged = temp;
  
    // while either firstNode or secondNode 
    // becomes NULL
    while(firstNode != NULL && 
          secondNode != NULL) 
    {    
        if(firstNode->data <= 
           secondNode->data) 
        {
            temp->next = firstNode;
            firstNode = firstNode->next;
        }
          
        else 
        {
            temp->next = secondNode;
            secondNode = secondNode->next;
        }
        temp = temp->next;
    }
     
   // Any remaining Node in firstNode or 
   // secondNode gets inserted in the temp 
   // List
    while(firstNode!=NULL) 
    {
        temp->next = firstNode;
        firstNode = firstNode->next;
        temp = temp->next;
    }
  
    while(secondNode!=NULL) 
    {
        temp->next = secondNode;
        secondNode = secondNode->next;
        temp = temp->next;
    }
  
    // Return the head of the sorted list
    return merged->next;
}
  
// Function to calculate the middle 
// Element
Node *middle(Node *head) 
{
    Node *slow = head;
    Node *fast = head->next;
     
    while(slow->next != NULL && 
         (fast!=NULL && fast->next!=NULL)) 
    {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}
  
// Function to sort the given list
Node *sort(Node *head)
{    
    if(head->next == NULL) 
    {
        return head;
    }
  
    Node *mid = new Node;
    Node *head2 = new Node;
    mid = middle(head);
    head2 = mid->next;   
    mid->next = NULL;
      
    // Recursive call to sort() hence diving 
    // our problem, and then merging the solution
    Node *finalhead = merge(sort(head),
                            sort(head2));  
    return finalhead;
}
  
int main(void
{
    Node *head = NULL;
    int n[] = {7, 10, 5, 20, 3, 2};
    for(int i = 0; i < 6; i++) 
    {
        // Inserting in the list
        insert(n[i], &head);   
    }
  
    cout << "Sorted Linked List is: ";
  
    // Printing the sorted list returned 
    // by sort()
    print(sort(head));     
    return 0;
}


Output:

Sorted Linked List is: 
2 3 5 7 10 20 

Time Complexity: O(n*log n)

Space Complexity: O(log n)

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



Last Updated : 17 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads