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

Practice this problem

Merge sort is an efficient, general-purpose sorting algorithm that produces a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. It is a comparison sort, i.e., it can sort items of any type for which a less-than relation is defined.

 
Merge sort is a Divide and Conquer algorithm. Like all divide-and-conquer algorithms, the merge sort algorithm splits the list into two sublists. Then it recursively sorts each sublist and finally merges both sorted lists together to form the answer. The following solution uses the frontBackSplit() and sortedMerge() method to solve this problem efficiently. We have already covered them in detail in previous posts.

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

C


Download  Run Code

Output:

1 —> 3 —> 4 —> 6 —> 8 —> 9 —> NULL

Java


Download  Run Code

Output:

1 —> 3 —> 4 —> 6 —> 8 —> 9 —> null

Python


Download  Run Code

Output:

1 —> 3 —> 4 —> 6 —> 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.

 
Using recursive stack space proportional to the length of a list is not recommended. However, in this case, recursion is okay as it uses stack space proportional to the log of the length of the list. For a 1000 node list, the recursion will only go about 10 levels deep. For a 2000 node list, it will go 11 levels deep. If we think about it, doubling the list’s size only increases the depth by 1.

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf