Given a singly linked list of integers, the task is to sort it using iterative merge sort.
Merge Sort is often preferred for sorting a linked list. It is discussed here. However, the method discussed above uses Stack for storing recursion calls. This may consume a lot of memory if the linked list to be sorted is too large. Hence, a purely iterative method for Merge Sort with no recursive calls is discussed in this post.
We use bottom-up approach of Merge Sort in this post. We know that Merge Sort first merges two items, then 4 items and so on. The idea is to use an integer variable to store the gap to find the midpoint around which the linked list needs to be sorted. So the problem reduces to merging two sorted Linked List which is discussed here. However, we do not use an additional list to keep the merged list. Instead we merge the lists within itself. The gap is incremented exponentially by 2 in each iteration and the process is repeated.
1 2 3 4 5 6 7
Time Complexity : O(n Log n)
Auxiliary Space : O(1)