Merge Sort in Java: Program and Logic
Sort an integer array in ascending order using merge sort.
- Time
O(n log n) - Space
O(n) - Hints3
- Read3 min
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.
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.
An integer array arr of length n.
The same array in ascending order.
Examples
[38, 27, 43, 3][3, 27, 38, 43][27, 38] and [3, 43] are merged.
[5, -1, 5, 2, 0][-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
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?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Split: find mid = left + (right - left) / 2. Sort left..mid, then sort
mid + 1..right.
Merge:
- Copy the range into a temporary array.
- Put
iat the start of the left half andjat the start of the right half. - Write the smaller of the two values back, and move that pointer.
- 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).
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
Solution
Reveal the full Java solution
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
temparray is made once and reused, so no new array is created in each call. j > rightmeans 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.
O(n log n)O(n)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
Merge Two Sorted Arrays Into One Sorted Array
Hints · Dry run · SolutionSolve Similar problemInsertion Sort in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemBinary Search in Java: Program and Logic
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningLoops
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
