Java Program for Merge Sort for Linked Lists Last Updated : 25 Oct, 2023 Comments Improve Suggest changes Like Article Like Report Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Let head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so head node has to be changed if the data at original head is not the smallest value in linked list. MergeSort(headRef) 1) If head is NULL or there is only one element in the Linked List then return. 2) Else divide the linked list into two halves. FrontBackSplit(head, &a, &b); /* a and b are two halves */ 3) Sort the two halves a and b. MergeSort(a); MergeSort(b); 4) Merge the sorted a and b (using SortedMerge() discussed here) and update the head pointer using headRef. *headRef = SortedMerge(a, b); Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Java // Java program to illustrate merge sorted // of linkedList public class linkedList { node head = null; // node a, b; static class node { int val; node next; public node(int val) { this.val = val; } } node sortedMerge(node a, node b) { node result = null; /* Base cases */ if (a == null) return b; if (b == null) return a; /* Pick either a or b, and recur */ if (a.val <= b.val) { result = a; result.next = sortedMerge(a.next, b); } else { result = b; result.next = sortedMerge(a, b.next); } return result; } node mergeSort(node h) { // Base case : if head is null if (h == null || h.next == null) { return h; } // get the middle of the list node middle = getMiddle(h); node nextofmiddle = middle.next; // set the next of middle node to null middle.next = null; // Apply mergeSort on left list node left = mergeSort(h); // Apply mergeSort on right list node right = mergeSort(nextofmiddle); // Merge the left and right lists node sortedlist = sortedMerge(left, right); return sortedlist; } // Utility function to get the middle of the linked list node getMiddle(node h) { // Base case if (h == null) return h; node fastptr = h.next; node slowptr = h; // Move fastptr by two and slow ptr by one // Finally slowptr will point to middle node while (fastptr != null) { fastptr = fastptr.next; if (fastptr != null) { slowptr = slowptr.next; fastptr = fastptr.next; } } return slowptr; } void push(int new_data) { /* allocate node */ node new_node = new node(new_data); /* link the old list off the new node */ new_node.next = head; /* move the head to point to the new node */ head = new_node; } // Utility function to print the linked list void printList(node headref) { while (headref != null) { System.out.print(headref.val + " "); headref = headref.next; } } public static void main(String[] args) { linkedList li = new linkedList(); /* * Let us create a unsorted linked lists to test the functions Created * lists shall be a: 2->3->20->5->10->15 */ li.push(15); li.push(10); li.push(5); li.push(20); li.push(3); li.push(2); System.out.println("Linked List without sorting is :"); li.printList(li.head); // Apply merge Sort li.head = li.mergeSort(li.head); System.out.print("\n Sorted Linked List is: \n"); li.printList(li.head); } } // This code is contributed by Rishabh Mahrsee Output: Linked List without sorting is : 2 3 20 5 10 15 Sorted Linked List is: 2 3 5 10 15 20 Time Complexity: O(n*log n) Auxiliary Space: O(n*log n) Please refer complete article on Merge Sort for Linked Lists for more details! Comment More infoAdvertise with us Next Article Java Program for Merge Sort for Linked Lists kartik Follow Improve Article Tags : Java Practice Tags : Java Similar Reads Java Program for Merge Sort Merge Sort is a divide-and-conquer algorithm. It divides the input array into two halves, calls itself the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are 3 min read LinkedHashMap and LinkedHashSet in Java The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements 3 min read SortedMap Interface in Java SortedMap is an interface in the collection framework that is a part of java.util package and extends the Map interface. It represents a map that maintains its keys in a sorted order. The keys in a SortedMap are sorted according to their natural ordering or by a Comparator provided at the time of ma 10 min read Different Ways of Array Sorting Techniques in Java with JUnit Accounting software /medical software / educational software etc. requires sorted data to be given for some analysis and also to prepare bar charts, pie charts, bar graphs, etc., In this tutorial let us see how to get sorted data in a java way. We need to know about the comparable interface and comp 6 min read Collections synchronizedSortedMap() method in Java with Examples The synchronizedSortedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) sorted map backed by the specified sorted map. In order to guarantee serial access, it is critical that all access to the backing sorted map is accomplished through the returned sorted ma 2 min read Collections synchronizedSortedSet() method in Java with Examples The synchronizedSortedSet() method of java.util.Collections class is used to return a synchronized (thread-safe) sorted set backed by the specified sorted set. In order to guarantee serial access, it is critical that all access to the backing sorted set is accomplished through the returned sorted se 2 min read Java Program For QuickSort On Singly Linked List QuickSort on Doubly Linked List is discussed here. QuickSort on Singly linked list was given as an exercise. The important things about implementation are, it changes pointers rather swapping data and time complexity is same as the implementation for Doubly Linked List. Recommended: Please solve it 3 min read Java Program to Merge Two Sorted Linked Lists in New List We are given two sorted List and our goal is to merge these two lists into a new list. For that, we have to write one function which will take two List as an argument which is sorted in increasing order. This function will Merge these two List into one List in increasing order. Input List 1 : 1-> 4 min read Java Program For Flattening A Linked List Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it 'right' pointer in the code below).Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below). All linked l 4 min read Java Program for Merge 3 Sorted Arrays Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D. Examples: Input : A = [1, 2, 3, 4, 5] B = [2, 3, 4] C = [4, 5, 6, 7] Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7] Input : A = [1, 2, 3, 5] B = [6, 7, 8 7 min read Like