Given a doubly linked list, sort it using the merge sort algorithm.

Practice this problem

Merge sort is an efficient sorting algorithm that uses the Divide and Conquer technique to sort a sequence of items. It is stable in nature, which means that the original order of equal elements is preserved in the output.

 
In the previous post, we have discussed the merge sort algorithm on a singly linked list. The merge sort algorithm on the doubly linked list works similarly by splitting the list into two halves, sorting each sublist recursively, and finally merge both the sorted lists together to get a single sorted list.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

1 ⇔ 2 ⇔ 4 ⇔ 6 ⇔ 7 ⇔ 8 ⇔ 9 ⇔ NULL

Java


Download  Run Code

Output:

1 ⇔ 2 ⇔ 4 ⇔ 6 ⇔ 7 ⇔ 8 ⇔ 9 ⇔ null

Python


Download  Run Code

Output:

1 ⇔ 2 ⇔ 4 ⇔ 6 ⇔ 7 ⇔ 8 ⇔ 9 ⇔ None

The time complexity of the above solution is O(n.log(n)), where n is the total number of nodes in the linked list, and doesn’t require any extra space.