Easy Array Problems Java

Merge Sort in Java: Program and Logic

Sort an integer array in ascending order using merge sort.

  • TimeO(n log n)
  • SpaceO(n)
  • Hints3
  • Read3 min
Quick answer

Merge sort in Java splits the array into two halves, sorts each half with recursion, and merges the two sorted halves using a temporary array. It takes O(n log n) time in every case and O(n) extra space. It is stable when the merge takes the left value on a tie.

Merge sortDivide and conquerRecursion
1

Problem statement

Write a program for merge sort in Java. Given an int array, sort it in ascending order without Arrays.sort.

The idea is divide and conquer. An array of one element is already sorted, and two sorted parts are easy to join. If that join step is new, solve merge two sorted arrays first.

Input

An integer array arr of length n.

Output

The same array in ascending order.

Examples

Example 1
Input[38, 27, 43, 3]
Output[3, 27, 38, 43]

[27, 38] and [3, 43] are merged.

Example 2
Input[5, -1, 5, 2, 0]
Output[-1, 0, 2, 5, 5]

An odd length works. One half is one element longer.

Constraints

  • 0 <= n <= 10^6
  • Duplicates and negative numbers are allowed
2

Think before you code

Reveal the questions to ask yourself first
  • What is the smallest array that needs no sorting?
  • Given two sorted halves, where is the smallest value of the whole?
  • Why does merging need a second array?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Base case: stop when left >= right.
2 Hint 2
Merge with two pointers, one for each half, and copy the smaller value each time.
3 Hint 3
One half will run out first. Copy what is left of the other half.
4

Approach

Reveal the step-by-step approach

Split: find mid = left + (right - left) / 2. Sort left..mid, then sort mid + 1..right.

Merge:

  1. Copy the range into a temporary array.
  2. Put i at the start of the left half and j at the start of the right half.
  3. Write the smaller of the two values back, and move that pointer.
  4. If one half is finished, take values from the other.

There are about log₂ n levels of splitting, and merging one level touches n elements. So the total time is O(n log n).

5

Dry run

Walk through the example step by step

[38, 27, 43, 3]:

split : [38, 27]           [43, 3]
split : [38] [27]          [43] [3]
merge : [27, 38]           [3, 43]
merge : [3, 27, 38, 43]

The last merge step by step:

left front | right front | written
-----------+-------------+--------
27         | 3           | 3
27         | 43          | 27
38         | 43          | 38
none       | 43          | 43
6

Solution

Reveal the full Java solution
Solution.java
import java.util.Arrays;

public class MergeSort {
    static void sort(int[] arr) {
        if (arr.length > 1) {
            sort(arr, new int[arr.length], 0, arr.length - 1);
        }
    }

    private static void sort(int[] arr, int[] temp, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = left + (right - left) / 2;
        sort(arr, temp, left, mid);
        sort(arr, temp, mid + 1, right);
        merge(arr, temp, left, mid, right);
    }

    private static void merge(int[] arr, int[] temp, int left, int mid, int right) {
        for (int k = left; k <= right; k++) {
            temp[k] = arr[k];
        }
        int i = left;
        int j = mid + 1;
        for (int k = left; k <= right; k++) {
            if (j > right || (i <= mid && temp[i] <= temp[j])) {
                arr[k] = temp[i++];
            } else {
                arr[k] = temp[j++];
            }
        }
    }

    public static void main(String[] args) {
        int[] a = {38, 27, 43, 3};
        sort(a);
        System.out.println(Arrays.toString(a));
        int[] b = {5, -1, 5, 2, 0};
        sort(b);
        System.out.println(Arrays.toString(b));
    }
}

This is merge sort in Java using recursion. Output:

[3, 27, 38, 43]
[-1, 0, 2, 5, 5]
  • One temp array is made once and reused, so no new array is created in each call.
  • j > right means the right half is finished, so take from the left half.
  • temp[i] <= temp[j] takes the left value on a tie. This keeps the sort stable.

Merge sort in Java without recursion

The bottom-up version merges blocks of size 1, then 2, then 4, until the block covers the array. It needs no call stack.

import java.util.Arrays;

public class MergeSortBottomUp {
    static void sort(int[] arr) {
        int n = arr.length;
        int[] temp = new int[n];
        for (int size = 1; size < n; size *= 2) {
            for (int left = 0; left < n - size; left += 2 * size) {
                int mid = left + size - 1;
                int right = Math.min(left + 2 * size - 1, n - 1);
                merge(arr, temp, left, mid, right);
            }
            System.out.println("size " + size + ": " + Arrays.toString(arr));
        }
    }

    static void merge(int[] arr, int[] temp, int left, int mid, int right) {
        for (int k = left; k <= right; k++) {
            temp[k] = arr[k];
        }
        int i = left, j = mid + 1;
        for (int k = left; k <= right; k++) {
            if (j > right || (i <= mid && temp[i] <= temp[j])) {
                arr[k] = temp[i++];
            } else {
                arr[k] = temp[j++];
            }
        }
    }

    public static void main(String[] args) {
        sort(new int[]{8, 3, 7, 4, 2, 6});
    }
}

Merge sort in Java example, with the array shown after each block size:

size 1: [3, 8, 4, 7, 2, 6]
size 2: [3, 4, 7, 8, 2, 6]
size 4: [2, 3, 4, 6, 7, 8]

Math.min handles the last block, which may be shorter. With array lengths far above our limit, size *= 2 could overflow, so use long there.

Complexity

Measure Recursive Bottom-up
Time, every case O(n log n) O(n log n)
Temporary array O(n) O(n)
Call stack O(log n) O(1)

Merge sort or quick sort?

Merge sort is stable and never slows to O(n²), but it needs extra memory. Quick sort sorts in place, but a bad pivot choice can make it O(n²). For very small arrays, insertion sort is simpler.

After this merge sort in Java program, practise explaining it aloud with the DSA interview questions. To build Java skills in order, see the Java full stack course.

TimeO(n log n)
SpaceO(n)
7

Review before the interview

Common mistakes

  • Recursing on left..mid - 1 and mid..right, which may never end.
  • Reading from arr while also writing to arr during the merge.
  • Forgetting to copy the rest of the half that is not finished.
  • Using < instead of <= in the merge, which makes the sort unstable.

Edge cases to test

  • Empty array or one element: return at once.
  • Two elements in the wrong order.
  • Odd length, where the halves differ by one.
  • All values equal, or already sorted.

Interview follow-ups

  • How would you count inversions during the merge?
  • Can you skip the merge if arr[mid] <= arr[mid + 1]? What does that do to the best case?
  • Why is merge sort a good fit for linked lists?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us