Java Program for Merge Sort for Linked Lists
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);
Java
public class linkedList {
node head = null ;
static class node {
int val;
node next;
public node( int val)
{
this .val = val;
}
}
node sortedMerge(node a, node b)
{
node result = null ;
if (a == null )
return b;
if (b == null )
return a;
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)
{
if (h == null || h.next == null ) {
return h;
}
node middle = getMiddle(h);
node nextofmiddle = middle.next;
middle.next = null ;
node left = mergeSort(h);
node right = mergeSort(nextofmiddle);
node sortedlist = sortedMerge(left, right);
return sortedlist;
}
node getMiddle(node h)
{
if (h == null )
return h;
node fastptr = h.next;
node slowptr = h;
while (fastptr != null ) {
fastptr = fastptr.next;
if (fastptr != null ) {
slowptr = slowptr.next;
fastptr = fastptr.next;
}
}
return slowptr;
}
void push( int new_data)
{
node new_node = new node(new_data);
new_node.next = head;
head = new_node;
}
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();
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);
li.head = li.mergeSort(li.head);
System.out.print( "\n Sorted Linked List is: \n" );
li.printList(li.head);
}
}
|
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!
Last Updated :
25 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...