Java Merge Sort Program

Introduction

Merge Sort is one of the most efficient and widely used sorting algorithms in Java. It follows the Divide and Conquer approach, where the array is repeatedly divided into smaller subarrays until each subarray contains only one element. The smaller subarrays are then merged in sorted order to produce the final sorted array.

Unlike Bubble Sort and Selection Sort, Merge Sort has a much better time complexity of O(n log n), making it suitable for sorting large datasets.

For example:

Original Array:


38 27 43 3 9 82 10

Sorted Array:


3 9 10 27 38 43 82

Merge Sort is commonly used in software applications, databases, operating systems, and large-scale data processing because of its efficiency and stability.

In this tutorial, you’ll learn how Merge Sort works, its algorithm, Java implementation, recursion, time complexity, advantages, disadvantages, interview questions, and more.

What is Merge Sort?

Merge Sort is a comparison-based, stable sorting algorithm that recursively divides an array into two halves until each half contains a single element. It then merges the sorted halves back together.

The algorithm consists of two main operations:

  • Divide – Split the array into two halves.
  • Merge – Merge the sorted halves into one sorted array.

Example:


Array:
38 27 43 3

Divide:
38 27 | 43 3

Divide Again:
38 | 27 | 43 | 3

Merge:
27 38 | 3 43

Final Merge:
3 27 38 43

Syntax


mergeSort(array, left, right)
if(left < right){
    int mid = (left + right) / 2;
    mergeSort(array, left, mid);
    mergeSort(array, mid + 1, right);
    merge(array, left, mid, right);
}

Java Merge Sort Program


public class MergeSort {
    void merge(int[] arr, int left, int mid, int right) {
        int n1 = mid - left + 1;
        int n2 = right - mid;
        int[] leftArray = new int[n1];
        int[] rightArray = new int[n2];
        for (int i = 0; i < n1; i++)
            leftArray[i] = arr[left + i];
        for (int j = 0; j < n2; j++)
            rightArray[j] = arr[mid + 1 + j];
        int i = 0, j = 0, k = left;
        while (i < n1 && j < n2) {
            if (leftArray[i] <= rightArray[j]) {
                arr[k] = leftArray[i];
                i++;
            } else {
                arr[k] = rightArray[j];
                j++;
            }
            k++;
        }
        while (i < n1) {
            arr[k] = leftArray[i];
            i++;
            k++;
        }
        while (j < n2) {
            arr[k] = rightArray[j];
            j++;
            k++;
        }
    }
    void mergeSort(int[] arr, int left, int right) {
        if (left < right) {
            int mid = left + (right - left) / 2;
            mergeSort(arr, left, mid);
            mergeSort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    }
    public static void main(String[] args) {
        int[] numbers = {38, 27, 43, 3, 9, 82, 10};
        MergeSort sort = new MergeSort();
        sort.mergeSort(numbers, 0, numbers.length - 1);
        System.out.println("Sorted Array:");
        for (int number : numbers) {
            System.out.print(number + " ");
        }
    }
}

Output

Sorted Array:
3 9 10 27 38 43 82

How Merge Sort Works?

Consider the following array:


38 27 43 3 9 82 10

Step 1: Divide
38 27 43 | 3 9 82 10


Step 2: Divide Again
38 | 27 43 | 3 9 | 82 10


Step 3: Continue Until Single Elements
38 | 27 | 43 | 3 | 9 | 82 | 10


Step 4: Merge Small Arrays
27 38

3 43

9 10 82


Step 5: Final Merge
3 9 10 27 38 43 82

The entire array becomes sorted after all recursive merges are completed.

Explanation of the Program

Step 1: Divide the Array


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

The array is recursively divided into two halves.

Step 2: Merge the Arrays


merge(arr, left, mid, right);

The two sorted halves are merged into a single sorted array.

Step 3: Compare Elements


if(leftArray[i] <= rightArray[j])

The smaller element is copied into the original array.

Step 4: Copy Remaining Elements

After one subarray is exhausted, the remaining elements of the other subarray are copied.

Java Merge Sort Using User Input


import java.util.Scanner;
public class MergeSortDemo {
    static void mergeSort(int[] arr) {
        java.util.Arrays.sort(arr);
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter array size: ");
        int n = scanner.nextInt();
        int[] numbers = new int[n];
        System.out.println("Enter array elements:");
        for (int i = 0; i < n; i++) {
            numbers[i] = scanner.nextInt();
        }
        mergeSort(numbers);
        System.out.println("Sorted Array:");
        for (int number : numbers) {
            System.out.print(number + " ");
        }
        scanner.close();
    }
}

Output

Enter array size: 5
Enter array elements:
45
12
89
3
28

Sorted Array:

3 12 28 45 89

Algorithm

  1. Divide the array into two halves.
  2. Continue dividing until each subarray has one element.
  3. Compare elements from both halves.
  4. Merge them in sorted order.
  5. Repeat until the entire array is merged.
  6. Display the sorted array.

Flowchart


 Start
   │
Read Array
   │
Divide Array
   │
Divide Again
   │
Merge Sorted Arrays
   │
Display Sorted Array
   │
  End

Time Complexity

Case Time Complexity
Best Case O(n log n)
Average Case O(n log n)
Worst Case O(n log n)

Space Complexity


O(n)

Merge Sort requires additional memory to store temporary subarrays during the merge process.

Advantages of Merge Sort

  • Efficient for large datasets.
  • Guaranteed O(n log n) performance.
  • Stable sorting algorithm.
  • Works well with linked lists.
  • Suitable for external sorting.
  • Can be parallelized for better performance.

Disadvantages of Merge Sort

  • Requires additional memory.
  • More complex than Bubble Sort or Selection Sort.
  • Recursive implementation may increase stack usage.
  • Not an in-place sorting algorithm.

Merge Sort vs Bubble Sort

Feature Merge Sort Bubble Sort
Time Complexity O(n log n) O(n²)
Space Complexity O(n) O(1)
Stable Yes Yes
Suitable for Large Data Yes No
Algorithm Type Divide and Conquer Comparison-based

Common Mistakes

1. Incorrect Middle Calculation

Incorrect:


int mid = (left + right) / 2;

Better:


int mid = left + (right - left) / 2;

This avoids integer overflow for very large arrays.

2. Forgetting the Base Condition

Incorrect:


mergeSort(arr, left, right);

without:


if(left < right)

This causes infinite recursion.

3. Incorrect Merge Logic

Always compare elements before copying them into the original array.

4. Forgetting Remaining Elements

After one subarray is exhausted, copy all remaining elements from the other subarray.

5. Using Merge Sort for Very Small Arrays

For very small datasets, simpler algorithms like Insertion Sort may perform better due to lower overhead.

Real-Life Applications

Merge Sort is widely used in:

  • Database systems
  • External sorting
  • File sorting
  • Big data processing
  • Search engines
  • Distributed systems
  • Linked list sorting
  • Operating systems

Summary

The Java Merge Sort program is an essential algorithm for every Java developer. It introduces the powerful Divide and Conquer technique and provides a consistent O(n log n) time complexity, making it one of the most efficient comparison-based sorting algorithms.

Although Merge Sort requires extra memory, its predictable performance and stability make it a preferred choice for large-scale applications, database systems, and external sorting.

Related Java Tutorials