# Merge Sort for Linked Lists using C++.

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

## Problem statement

Given a linked list. Sort it using merge sort algorithm

List: 10->20->8-17->5->13->4
Sorted list: 4->5->8->10->13->17->20

## Algorithm

1. If head is NULL or list contains only one element then return list
2. Create two lists by dividing original list into 2 parts
3. Sort first and second part of list
4. Merge both sorted list

## Example

#include <iostream>
#include <new>
#define SIZE(arr) (sizeof(arr) / sizeof(arr))
using namespace std;
struct node {
int data;
struct node *next;
};
node *createList(int *arr, int n){
p = head = new node;
for (int i = 1; i < n; ++i) {
p->next = new node;
p = p->next;
p->data = arr[i];
p->next = NULL;
}
}
while (head != NULL) {
cout << head->data << " ";
}
cout << endl;
}
node *result = NULL;
if (head1 == NULL) {
}
if (head2 == NULL) {
}
} else {
}
return result;
}
void splitList(node *src, node **fRef, node **bRef){
node *fast;
node *slow;
slow = src;
fast = src->next;
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
*fRef = src;
*bRef = slow->next;
slow->next = NULL;
}
node *p = *head;
node *a = NULL;
node *b = NULL;
if (p == NULL || p->next == NULL) {
return;
}
splitList(p, &a, &b);
mergeSort(&a);
mergeSort(&b);
*head = mergeSortedLists(a, b);
}
int main(){
int arr[] = {10, 20, 8, 17, 5, 13, 4};
head = createList(arr, SIZE(arr));
cout << "Unsorted list: " << endl;
cout << "Final sorted list: " << endl;
}
Unsorted list:
4 5 8 10 13 17 20