Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this Java DSA implementation can be compared directly with the other languages.
Basic Implementation
Basic.java
class Basic {
public static void main(String[] args) {
int[] arr = new int[] { 5, 1, 4, 2, 8 };
int[] sorted = mergeSort(arr);
printArray(sorted);
}
static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print(arr[i]);
}
System.out.println("]");
}
static int[] mergeSort(int[] values) {
if (values.length <= 1) return values;
int mid = values.length / 2;
int[] left = java.util.Arrays.copyOfRange(values, 0, mid);
int[] right = java.util.Arrays.copyOfRange(values, mid, values.length);
return merge(mergeSort(left), mergeSort(right));
}
static int[] merge(int[] left, int[] right) {
int[] merged = new int[left.length + right.length];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) merged[k++] = left[i++];
else merged[k++] = right[j++];
}
while (i < left.length) merged[k++] = left[i++];
while (j < right.length) merged[k++] = right[j++];
return merged;
}
}
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
- Keep the explicit algorithmic steps instead of calling a standard-library sort. The replay is meant to expose comparisons, movement, and recursion.
- The implementation is intentionally compact for learning and replay, not a production sorting utility.
divide and conquer
Each recursive call solves a smaller sorted subproblem.
merge step
Two sorted halves are combined by repeatedly taking the smaller front item.