Hence, we will create a new node with the same value and return this new node. When we have only one node in the range, then this node is already sorted. Q) What should be the base case of the recursive merge sort function?
Sort linked list how to#
We know how to merge two sorted linked lists, right? I am not going to explain how to write the merge operation, which we wrote earlier.Now, we need to merge these sorted linked lists into a single linked list, which should be sorted as well.
We have two linked lists which are in sorted order separately.Q) How to combine the results of smaller subproblems to solve the current larger problem, i.e. On calling mergeSort recursively, we will get two new sorted lists. call mergeSort to sort the left part (from head to mid) and also call mergeSort to sort the right part (from mid->next to tail). We will recursively call for the smaller subproblem, i.e.
So, now we know how to find smaller subproblems. Solution 1: Brute Force Using Insertion Sort (brutesolution.java) Create an empty sorted list (in our code, it is sortedListHead) Traverse the given list, do. We will use the function mid() which we wrote earlier directly. I am not going to explain how to find the middle node of the linked list in this article again.We know how to get the middle node of a linked list in one traversal using the concept of slow and fast pointers, right?.In the linked list, to get the middle node of the current range, we will have to do a traversal of the current range, as we cannot get direct access to the middle node.But, in arrays, getting the middle index to split the left & right ranges is easy, as we can randomly access any index in O(1) constant time.Similar to what we did in arrays, we will sort the first half of the linked list and the second half of the linked list separately.Q) How to divide the problem into subproblems? How can we use the concept we learnt there to solve this problem?Īs we know that merge sort is a Divide & Conquer Algorithm, we can solve a larger subproblem by dividing the problem into subproblems recursively, and combining the solved smaller problem to solve the larger problem. We know how to merge-sort an unsorted array. Reverse Linked List (pointer - Recursive) The next step is tot sort these two lists seperately. Less contains all items less than or equal to the pivot, and more contains the rest (items that are larger than the pivot). Then split the remaining items in two lists: less and more. Remove Duplicates In A Sorted Linked Listĭisplay Reverse (recursive) - Linked List This quicksort works like this: Select the first item as the pivot.