Easy Sorting Algorithms to Sort a Linked List

Merge Sort for Linked Lists

View Discussion

Improve Article

Save Article

Like Article

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.

sorting image

Let the 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 the head node has to be changed if the data at the original head is not the smallest value in the linked list.

MergeSort(headRef) 1) If the 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);

Complete Interview Preparation - GFG

C++

#include <bits/stdc++.h>

using namespace std;

class Node {

public :

int data;

Node* next;

};

Node* SortedMerge(Node* a, Node* b);

void FrontBackSplit(Node* source,

Node** frontRef, Node** backRef);

void MergeSort(Node** headRef)

{

Node* head = *headRef;

Node* a;

Node* b;

if ((head == NULL) || (head->next == NULL)) {

return ;

}

FrontBackSplit(head, &a, &b);

MergeSort(&a);

MergeSort(&b);

*headRef = SortedMerge(a, b);

}

Node* SortedMerge(Node* a, Node* b)

{

Node* result = NULL;

if (a == NULL)

return (b);

else if (b == NULL)

return (a);

if (a->data <= b->data) {

result = a;

result->next = SortedMerge(a->next, b);

}

else {

result = b;

result->next = SortedMerge(a, b->next);

}

return (result);

}

void FrontBackSplit(Node* source,

Node** frontRef, Node** backRef)

{

Node* fast;

Node* slow;

slow = source;

fast = source->next;

while (fast != NULL) {

fast = fast->next;

if (fast != NULL) {

slow = slow->next;

fast = fast->next;

}

}

*frontRef = source;

*backRef = slow->next;

slow->next = NULL;

}

void printList(Node* node)

{

while (node != NULL) {

cout << node->data << " " ;

node = node->next;

}

}

void push(Node** head_ref, int new_data)

{

Node* new_node = new Node();

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;

}

int main()

{

Node* res = NULL;

Node* a = NULL;

push(&a, 15);

push(&a, 10);

push(&a, 5);

push(&a, 20);

push(&a, 3);

push(&a, 2);

MergeSort(&a);

cout << "Sorted Linked List is: \n" ;

printList(a);

return 0;

}

C

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

struct Node* SortedMerge( struct Node* a, struct Node* b);

void FrontBackSplit( struct Node* source,

struct Node** frontRef, struct Node** backRef);

void MergeSort( struct Node** headRef)

{

struct Node* head = *headRef;

struct Node* a;

struct Node* b;

if ((head == NULL) || (head->next == NULL)) {

return ;

}

FrontBackSplit(head, &a, &b);

MergeSort(&a);

MergeSort(&b);

*headRef = SortedMerge(a, b);

}

struct Node* SortedMerge( struct Node* a, struct Node* b)

{

struct Node* result = NULL;

if (a == NULL)

return (b);

else if (b == NULL)

return (a);

if (a->data <= b->data) {

result = a;

result->next = SortedMerge(a->next, b);

}

else {

result = b;

result->next = SortedMerge(a, b->next);

}

return (result);

}

void FrontBackSplit( struct Node* source,

struct Node** frontRef, struct Node** backRef)

{

struct Node* fast;

struct Node* slow;

slow = source;

fast = source->next;

while (fast != NULL) {

fast = fast->next;

if (fast != NULL) {

slow = slow->next;

fast = fast->next;

}

}

*frontRef = source;

*backRef = slow->next;

slow->next = NULL;

}

void printList( struct Node* node)

{

while (node != NULL) {

printf ( "%d " , node->data);

node = node->next;

}

}

void push( struct Node** head_ref, int new_data)

{

struct Node* new_node = ( struct Node*) malloc ( sizeof ( struct Node));

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;

}

int main()

{

struct Node* res = NULL;

struct Node* a = NULL;

push(&a, 15);

push(&a, 10);

push(&a, 5);

push(&a, 20);

push(&a, 3);

push(&a, 2);

MergeSort(&a);

printf ( "Sorted Linked List is: \n" );

printList(a);

getchar ();

return 0;

}

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;

}

public static node getMiddle(node head)

{

if (head == null )

return head;

node slow = head, fast = head;

while (fast.next != null && fast.next.next != null ) {

slow = slow.next;

fast = fast.next.next;

}

return slow;

}

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 );

li.head = li.mergeSort(li.head);

System.out.print( "\n Sorted Linked List is: \n" );

li.printList(li.head);

}

}

Python3

class Node:

def __init__( self , data):

self .data = data

self . next = None

class LinkedList:

def __init__( self ):

self .head = None

def append( self , new_value):

new_node = Node(new_value)

if self .head is None :

self .head = new_node

return

curr_node = self .head

while curr_node. next is not None :

curr_node = curr_node. next

curr_node. next = new_node

def sortedMerge( self , a, b):

result = None

if a = = None :

return b

if b = = None :

return a

if a.data < = b.data:

result = a

result. next = self .sortedMerge(a. next , b)

else :

result = b

result. next = self .sortedMerge(a, b. next )

return result

def mergeSort( self , h):

if h = = None or h. next = = None :

return h

middle = self .getMiddle(h)

nexttomiddle = middle. next

middle. next = None

left = self .mergeSort(h)

right = self .mergeSort(nexttomiddle)

sortedlist = self .sortedMerge(left, right)

return sortedlist

def getMiddle( self , head):

if (head = = None ):

return head

slow = head

fast = head

while (fast. next ! = None and

fast. next . next ! = None ):

slow = slow. next

fast = fast. next . next

return slow

def printList(head):

if head is None :

print ( ' ' )

return

curr_node = head

while curr_node:

print (curr_node.data, end = " " )

curr_node = curr_node. next

print ( ' ' )

if __name__ = = '__main__' :

li = LinkedList()

li.append( 15 )

li.append( 10 )

li.append( 5 )

li.append( 20 )

li.append( 3 )

li.append( 2 )

li.head = li.mergeSort(li.head)

print ( "Sorted Linked List is:" )

printList(li.head)

C#

using System;

public class linkedList {

node head = null ;

public class node {

public int val;

public 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 ) {

Console.Write(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);

li.head = li.mergeSort(li.head);

Console.Write( "\n Sorted Linked List is: \n" );

li.printList(li.head);

}

}

Javascript

<script>

var head = null ;

class node {

constructor(val) {

this .val = val;

this .next = null ;

}

}

function sortedMerge( a,  b)

{

var 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;

}

function mergeSort( h) {

if (h == null || h.next == null ) {

return h;

}

var middle = getMiddle(h);

var nextofmiddle = middle.next;

middle.next = null ;

var left = mergeSort(h);

var right = mergeSort(nextofmiddle);

var sortedlist = sortedMerge(left, right);

return sortedlist;

}

function getMiddle( head) {

if (head == null )

return head;

var slow = head, fast = head;

while (fast.next != null && fast.next.next != null )

{

slow = slow.next;

fast = fast.next.next;

}

return slow;

}

function push(new_data) {

var new_node = new node(new_data);

new_node.next = head;

head = new_node;

}

function printList( headref) {

while (headref != null ) {

document.write(headref.val + " " );

headref = headref.next;

}

}

push(15);

push(10);

push(5);

push(20);

push(3);

push(2);

head = mergeSort(head);

document.write( "\n Sorted Linked List is: \n" );

printList(head);

</script>

Output:

Sorted Linked List is:  2 3 5 10 15 20

Time Complexity: O(n*log n)

Auxiliary Space: O(n)

Approach 2: This approach is simpler and uses log n space.

mergeSort():

  1. If the size of the linked list is 1 then return the head
  2. Find mid using The Tortoise and The Hare Approach
  3. Store the next of mid in head2 i.e. the right sub-linked list.
  4. Now Make the next midpoint null.
  5. Recursively call mergeSort() on both left and right sub-linked list and store the new head of the left and right linked list.
  6. Call merge() given the arguments new heads of left and right sub-linked lists and store the final head returned after merging.
  7. Return the final head of the merged linkedlist.

merge(head1, head2):

  1. Take a pointer say merged to store the merged list in it and store a dummy node in it.
  2. Take a pointer temp and assign merge to it.
  3. If the data of head1 is less than the data of head2, then, store head1 in next of temp & move head1 to the next of head1.
  4. Else store head2 in next of temp & move head2 to the next of head2.
  5. Move temp to the next of temp.
  6. Repeat steps 3, 4 & 5 until head1 is not equal to null and head2 is not equal to null.
  7. Now add any remaining nodes of the first or the second linked list to the merged linked list.
  8. Return the next of merged(that will ignore the dummy and return the head of the final merged linked list)

C++

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

};

void insert( int x, Node** head)

{

if (*head == NULL) {

*head = new Node;

(*head)->data = x;

(*head)->next = NULL;

return ;

}

Node* temp = new Node;

temp->data = (*head)->data;

temp->next = (*head)->next;

(*head)->data = x;

(*head)->next = temp;

}

void print(Node* head)

{

Node* temp = head;

while (temp != NULL) {

cout << temp->data << " " ;

temp = temp->next;

}

}

Node* merge(Node* firstNode, Node* secondNode)

{

Node* merged = new Node;

Node* temp = new Node;

merged = temp;

while (firstNode != NULL && secondNode != NULL) {

if (firstNode->data <= secondNode->data) {

temp->next = firstNode;

firstNode = firstNode->next;

}

else {

temp->next = secondNode;

secondNode = secondNode->next;

}

temp = temp->next;

}

while (firstNode != NULL) {

temp->next = firstNode;

firstNode = firstNode->next;

temp = temp->next;

}

while (secondNode != NULL) {

temp->next = secondNode;

secondNode = secondNode->next;

temp = temp->next;

}

return merged->next;

}

Node* middle(Node* head)

{

Node* slow = head;

Node* fast = head->next;

while (!slow->next && (!fast && !fast->next)) {

slow = slow->next;

fast = fast->next->next;

}

return slow;

}

Node* sort(Node* head)

{

if (head->next == NULL) {

return head;

}

Node* mid = new Node;

Node* head2 = new Node;

mid = middle(head);

head2 = mid->next;

mid->next = NULL;

Node* finalhead = merge(sort(head), sort(head2));

return finalhead;

}

int main( void )

{

Node* head = NULL;

int n[] = { 7, 10, 5, 20, 3, 2 };

for ( int i = 0; i < 6; i++) {

insert(n[i], &head);

}

cout << "Sorted Linked List is: \n" ;

print(sort(head));

return 0;

}

C

#include <stdio.h>

#include <stdlib.h>

typedef struct Node {

int data;

struct Node* next;

} Node;

void insert( int x, Node** head)

{

if (*head == NULL) {

*head = (Node*) malloc ( sizeof (Node));

(*head)->data = x;

(*head)->next = NULL;

return ;

}

Node* temp = (Node*) malloc ( sizeof (Node));

temp->data = (*head)->data;

temp->next = (*head)->next;

(*head)->data = x;

(*head)->next = temp;

}

void print(Node* head)

{

Node* temp = head;

while (temp != NULL) {

printf ( "%d " , temp->data);

temp = temp->next;

}

}

Node* merge(Node* firstNode, Node* secondNode)

{

Node* merged = (Node*) malloc ( sizeof (Node));

Node* temp = (Node*) malloc ( sizeof (Node));

merged = temp;

while (firstNode != NULL && secondNode != NULL) {

if (firstNode->data <= secondNode->data) {

temp->next = firstNode;

firstNode = firstNode->next;

}

else {

temp->next = secondNode;

secondNode = secondNode->next;

}

temp = temp->next;

}

while (firstNode != NULL) {

temp->next = firstNode;

firstNode = firstNode->next;

temp = temp->next;

}

while (secondNode != NULL) {

temp->next = secondNode;

secondNode = secondNode->next;

temp = temp->next;

}

return merged->next;

}

Node* middle(Node* head)

{

Node* slow = head;

Node* fast = head->next;

while (!slow->next && (!fast && !fast->next)) {

slow = slow->next;

fast = fast->next->next;

}

return slow;

}

Node* sort(Node* head)

{

if (head->next == NULL) {

return head;

}

Node* mid = (Node*) malloc ( sizeof (Node));

Node* head2 = (Node*) malloc ( sizeof (Node));

mid = middle(head);

head2 = mid->next;

mid->next = NULL;

Node* finalhead = merge(sort(head), sort(head2));

return finalhead;

}

int main( void )

{

Node* head = NULL;

int n[] = { 7, 10, 5, 20, 3, 2 };

for ( int i = 0; i < 6; i++) {

insert(n[i], &head);

}

printf ( "Sorted Linked List is: \n" );

print(sort(head));

return 0;

}

Java

import java.io.*;

import java.lang.*;

import java.util.*;

class Node {

int data;

Node next;

Node( int key)

{

this .data = key;

next = null ;

}

}

class GFG {

static Node mergeSort(Node head)

{

if (head.next == null )

return head;

Node mid = findMid(head);

Node head2 = mid.next;

mid.next = null ;

Node newHead1 = mergeSort(head);

Node newHead2 = mergeSort(head2);

Node finalHead = merge(newHead1, newHead2);

return finalHead;

}

static Node merge(Node head1, Node head2)

{

Node merged = new Node(- 1 );

Node temp = merged;

while (head1 != null && head2 != null ) {

if (head1.data < head2.data) {

temp.next = head1;

head1 = head1.next;

}

else {

temp.next = head2;

head2 = head2.next;

}

temp = temp.next;

}

while (head1 != null ) {

temp.next = head1;

head1 = head1.next;

temp = temp.next;

}

while (head2 != null ) {

temp.next = head2;

head2 = head2.next;

temp = temp.next;

}

return merged.next;

}

static Node findMid(Node head)

{

Node slow = head, fast = head.next;

while (fast != null && fast.next != null ) {

slow = slow.next;

fast = fast.next.next;

}

return slow;

}

static void printList(Node head)

{

while (head != null ) {

System.out.print(head.data + " " );

head = head.next;

}

}

public static void main(String[] args)

{

Node head = new Node( 7 );

Node temp = head;

temp.next = new Node( 10 );

temp = temp.next;

temp.next = new Node( 5 );

temp = temp.next;

temp.next = new Node( 20 );

temp = temp.next;

temp.next = new Node( 3 );

temp = temp.next;

temp.next = new Node( 2 );

temp = temp.next;

head = mergeSort(head);

System.out.print( "\nSorted Linked List is: \n" );

printList(head);

}

}

Python3

class Node:

def __init__( self ,key):

self .data = key

self . next = None

def mergeSort(head):

if (head. next = = None ):

return head

mid = findMid(head)

head2 = mid. next

mid. next = None

newHead1 = mergeSort(head)

newHead2 = mergeSort(head2)

finalHead = merge(newHead1, newHead2)

return finalHead

def merge(head1,head2):

merged = Node( - 1 )

temp = merged

while (head1 ! = None and head2 ! = None ):

if (head1.data < head2.data):

temp. next = head1

head1 = head1. next

else :

temp. next = head2

head2 = head2. next

temp = temp. next

while (head1 ! = None ):

temp. next = head1

head1 = head1. next

temp = temp. next

while (head2 ! = None ):

temp. next = head2

head2 = head2. next

temp = temp. next

return merged. next

def findMid(head):

slow = head

fast = head. next

while (fast ! = None and fast. next ! = None ):

slow = slow. next

fast = fast. next . next

return slow

def printList(head):

while (head ! = None ):

print (head.data,end = " " )

head = head. next

head = Node( 7 )

temp = head

temp. next = Node( 10 );

temp = temp. next ;

temp. next = Node( 5 );

temp = temp. next ;

temp. next = Node( 20 );

temp = temp. next ;

temp. next = Node( 3 );

temp = temp. next ;

temp. next = Node( 2 );

temp = temp. next ;

head = mergeSort(head);

print ( "\nSorted Linked List is: \n" );

printList(head);

C#

using System;

public class Node

{

public int data;

public Node next;

public Node( int key)

{

this .data = key;

next = null ;

}

}

class GFG{

static Node mergeSort(Node head)

{

if (head.next == null )

return head;

Node mid = findMid(head);

Node head2 = mid.next;

mid.next = null ;

Node newHead1 = mergeSort(head);

Node newHead2 = mergeSort(head2);

Node finalHead = merge(newHead1, newHead2);

return finalHead;

}

static Node merge(Node head1, Node head2)

{

Node merged = new Node(-1);

Node temp = merged;

while (head1 != null && head2 != null )

{

if (head1.data < head2.data)

{

temp.next = head1;

head1 = head1.next;

}

else

{

temp.next = head2;

head2 = head2.next;

}

temp = temp.next;

}

while (head1 != null )

{

temp.next = head1;

head1 = head1.next;

temp = temp.next;

}

while (head2 != null )

{

temp.next = head2;

head2 = head2.next;

temp = temp.next;

}

return merged.next;

}

static Node findMid(Node head)

{

Node slow = head, fast = head.next;

while (fast != null && fast.next != null )

{

slow = slow.next;

fast = fast.next.next;

}

return slow;

}

static void printList(Node head)

{

while (head != null )

{

Console.Write(head.data + " " );

head = head.next;

}

}

public static void Main(String[] args)

{

Node head = new Node(7);

Node temp = head;

temp.next = new Node(10);

temp = temp.next;

temp.next = new Node(5);

temp = temp.next;

temp.next = new Node(20);

temp = temp.next;

temp.next = new Node(3);

temp = temp.next;

temp.next = new Node(2);

temp = temp.next;

head = mergeSort(head);

Console.Write( "\nSorted Linked List is: \n" );

printList(head);

}

}

Javascript

<script>

class Node {

constructor(val) {

this .data = val;

this .next = null ;

}

}

function mergeSort(head) {

if (head.next == null )

return head;

var mid = findMid(head);

var head2 = mid.next;

mid.next = null ;

var newHead1 = mergeSort(head);

var newHead2 = mergeSort(head2);

var finalHead = merge(newHead1, newHead2);

return finalHead;

}

function merge(head1,  head2) {

var merged = new Node(-1);

var temp = merged;

while (head1 != null && head2 != null ) {

if (head1.data < head2.data) {

temp.next = head1;

head1 = head1.next;

} else {

temp.next = head2;

head2 = head2.next;

}

temp = temp.next;

}

while (head1 != null ) {

temp.next = head1;

head1 = head1.next;

temp = temp.next;

}

while (head2 != null ) {

temp.next = head2;

head2 = head2.next;

temp = temp.next;

}

return merged.next;

}

function findMid(head) {

var slow = head, fast = head.next;

while (fast != null && fast.next != null ) {

slow = slow.next;

fast = fast.next.next;

}

return slow;

}

function printList(head) {

while (head != null ) {

document.write(head.data + " " );

head = head.next;

}

}

var head = new Node(7);

var temp = head;

temp.next = new Node(10);

temp = temp.next;

temp.next = new Node(5);

temp = temp.next;

temp.next = new Node(20);

temp = temp.next;

temp.next = new Node(3);

temp = temp.next;

temp.next = new Node(2);

temp = temp.next;

head = mergeSort(head);

document.write( "Sorted Linked List is: <br/>" );

printList(head);

</script>

Output:

Sorted Linked List is:  2 3 5 7 10 20          

Time Complexity: O(n*log n)

Auxiliary Space: O(n)

Sources:
http://en.wikipedia.org/wiki/Merge_sort
http://cslibrary.stanford.edu/105/LinkedListProblems.pdf

Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.


lowehessium.blogspot.com

Source: https://www.geeksforgeeks.org/merge-sort-for-linked-list/

0 Response to "Easy Sorting Algorithms to Sort a Linked List"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel