Java Program to Implement Merge Sort on n Numbers Without tail-recursion

Problem Description

Given an array of integers, sort the array using merge sort algorithm.

Problem Solution

The idea is to divide the array into two equal parts. Recursively sort the two parts of the array and finally merge them.Program/Source Code

Here is the source code of the Java Program to Implement Merge Sort on n Numbers Without tail-recursion. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

//Java Program to Implement Merge Sort on n Numbers Without tail-recursion
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
 
public class MergeSort {
    // Function to merge the two sorted arrays
    static void merge(int[] array,int low,int mid,int high){
        int i,j,k;
        int[] c= new int[high-low+1];
        k = 0;
        i=low;
        j=mid+1;
        while(i<=mid && j<=high){
            if(array[i]<=array[j]){
                c[k++] = array[i++];
            }
            else{
                c[k++] = array[j++];
            }
        }
        while(i<=mid){
            c[k++] = array[i++];
        }
        while(j<=high){
            c[k++] = array[j++];
        }
        k=0;
        for(i = low; i<=high; i++){
            array[i] = c[k++];
        }
    }
    // Function implementing the merge sort
    static void mergeSort(int[] array,int low, int high){
        if(high-low+1>1){
            int mid = (low+high)/2;
            mergeSort(array,low,mid);
            mergeSort(array,mid+1,high);
            merge(array,low,mid,high);
        }
    }
    // Function to read the input and display the output
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int size;
        System.out.println("Enter the size of the array");
        try {
            size = Integer.parseInt(br.readLine());
        } catch (Exception e) {
            System.out.println("Invalid Input");
            return;
        }
        int[] array = new int[size];
        System.out.println("Enter array elements");
        int i;
        for (i = 0; i < array.length; i++) {
            try {
                array[i] = Integer.parseInt(br.readLine());
            } catch (Exception e) {
                System.out.println("An error Occurred");
            }
        }
        System.out.println("The initial array is");
        System.out.println(Arrays.toString(array));
        mergeSort(array,0,array.length-1);
        System.out.println("The sorted array is");
        System.out.println(Arrays.toString(array));
    }
}

Program Explanation

1. In function mergeSort(), first, we check if there is more than one element in the array, through the condition if(high-low+1>1).
2. If that is the case, a recursive call is made on the two halves obtained by dividing the array.
3. In function merge(), the while(i<=mid && j<=high) loop merges the elements of the two array into the new array c.
4. The loops while(i<=mid) and while(j<=high), adds any remaining elements of the arrays, at the end of c.

Time Complexity: O(n*log(n)) where n is the number of elements in the array.

Runtime Test Cases

Case 1 (Simple Test Case):
 
Enter the size of the array
5
Enter array elements
5
4
3
2
1
The initial array is
[5, 4, 3, 2, 1]
The sorted array is
[1, 2, 3, 4, 5]
 
Case 2 (Simple Test Case - another example):
 
Enter the size of the array
8
Enter array elements
4
3
2
1
1
2
3
4
The initial array is
[4, 3, 2, 1, 1, 2, 3, 4]
The sorted array is
[1, 1, 2, 2, 3, 3, 4, 4]

Related posts:

Adding a Newline Character to a String in Java
Java Program to Implement IdentityHashMap API
Java Program to Implement Nth Root Algorithm
Java Program to Implement Heap Sort Using Library Functions
Java Program for Douglas-Peucker Algorithm Implementation
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
What is a POJO Class?
Life Cycle of a Thread in Java
How to Get the Last Element of a Stream in Java?
HttpClient 4 – Follow Redirects for POST
Java Program to Implement DelayQueue API
Custom Exception trong Java
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Hướng dẫn Java Design Pattern – MVC
Using Optional with Jackson
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Java Convenience Factory Methods for Collections
Quick Guide to Spring Controllers
Spring Cloud – Securing Services
Java Program to Implement Skip List
Spring Boot - Runners
Java Program to Show the Duality Transformation of Line and Point
Performance Difference Between save() and saveAll() in Spring Data
File Upload with Spring MVC
Collect a Java Stream to an Immutable Collection
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Spring Boot - Apache Kafka
Hướng dẫn Java Design Pattern – Transfer Object
Introduction to Spring Cloud Stream
Quick Guide to Spring Bean Scopes