Java Program to Implement Merge Sort Algorithm on Linked List

This is a java program to implement merge sort algorithm using linked list.

Here is the source code of the Java Program to Implement Merge Sort Algorithm on Linked List. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

//This is a java to sort numbers of Linked List using Merge Sort
import java.util.Random;
 
class Node 
{
    public int item;
    public Node next;
 
    public Node(int val) 
    {
        item = val;
    }
 
    public Node() 
    {}
 
    public void displayNode() 
    {
        System.out.print("[" + item + "] ");
    }
}
 
class LinkedList 
{
    private Node first;
 
    public LinkedList() 
    {
        first = null;
    }
 
    public boolean isEmpty() 
    {
        return (first == null);
    }
 
    public void insert(int val)
    {
        Node newNode = new Node(val);
        newNode.next = first;
        first = newNode;
    }
 
    public void append(Node result) 
    {
        first = result;
    }
 
    public void display() 
    {
        Node current = first;
        while (current != null) 
        {
            current.displayNode();
            current = current.next;
        }
        System.out.println("");
    }
 
    public Node extractFirst() 
    {
        return first;
    }
 
    public Node MergeSort(Node headOriginal) 
    {
        if (headOriginal == null || headOriginal.next == null)
            return headOriginal;
        Node a = headOriginal;
        Node b = headOriginal.next;
        while ((b != null) && (b.next != null)) 
        {
            headOriginal = headOriginal.next;
            b = (b.next).next;
        }
        b = headOriginal.next;
        headOriginal.next = null;
        return merge(MergeSort(a), MergeSort(b));
    }
 
    public Node merge(Node a, Node b) 
    {
        Node temp = new Node();
        Node head = temp;
        Node c = head;
        while ((a != null) && (b != null)) 
        {
            if (a.item <= b.item) 
            {
                c.next = a;
                c = a;
                a = a.next;
            }
            else 
            {
                c.next = b;
                c = b;
                b = b.next;
            }
        }
        c.next = (a == null) ? b : a;
        return head.next;
    }
}
 
class Merge_Sort 
{
    public static void main(String[] args) 
    {
        LinkedList object = new LinkedList();
        Random random = new Random();
        int N = 20;
        for (int i = 0; i < N; i++)
            object.insert(Math.abs(random.nextInt(100)));
 
        System.out.println("List items before sorting :");
        object.display();
        object.append(object.MergeSort(object.extractFirst()));
        System.out.println("List items after sorting :");
        object.display();
    }
}

Output:

$ javac Merge_Sort.java
$ java Merge_Sort
 
List items before sorting :
[41] [11] [6] [13] [41] [62] [26] [46] [71] [16] [52] [57] [23] [81] [25] [4] [20] [75] [68] [51] 
List items after sorting :
[4] [6] [11] [13] [16] [20] [23] [25] [26] [41] [41] [46] [51] [52] [57] [62] [68] [71] [75] [81]

Related posts:

Spring Cloud AWS – Messaging Support
Java Program to Implement Sieve Of Atkin
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java InputStream to String
The Java 8 Stream API Tutorial
Hướng dẫn Java Design Pattern – Dependency Injection
Java Program to Implement LinkedList API
Java Program to Implement Stack using Two Queues
Tips for dealing with HTTP-related problems
Difference Between Wait and Sleep in Java
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
New Features in Java 12
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Java Program to Implement Hamiltonian Cycle Algorithm
Ignore Null Fields with Jackson
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Introduction to Spring Method Security
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Implement RoleUnresolvedList API
Java Program to Check whether Undirected Graph is Connected using BFS
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
A Guide to Java SynchronousQueue
A Guide to @RepeatedTest in Junit 5
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Java Program to Implement Counting Sort
Java Program to Check Whether a Given Point is in a Given Polygon
Java Program to Implement Fenwick Tree
Spring REST API + OAuth2 + Angular
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Easy Ways to Write a Java InputStream to an OutputStream
Java 8 StringJoiner
Semaphore trong Java