Implementing the Base Case in Java Merge Sort
Now that we have defined the base case in the Merge Sort algorithm, let's dive into the implementation details in Java.
Implementing the Base Case
The base case in the Merge Sort algorithm is implemented by checking the length of the input array or subarray. If the length is 1 or 2, the algorithm returns the array as is or the sorted array of two elements.
Here's an example implementation of the Merge Sort algorithm in Java, including the base case handling:
public static int[] mergeSort(int[] arr) {
if (arr.length <= 1) {
return arr;
}
int mid = arr.length / 2;
int[] left = Arrays.copyOfRange(arr, 0, mid);
int[] right = Arrays.copyOfRange(arr, mid, arr.length);
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
private static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int leftIndex = 0, rightIndex = 0, resultIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
result[resultIndex++] = left[leftIndex++];
} else {
result[resultIndex++] = right[rightIndex++];
}
}
while (leftIndex < left.length) {
result[resultIndex++] = left[leftIndex++];
}
while (rightIndex < right.length) {
result[resultIndex++] = right[rightIndex++];
}
return result;
}
In this implementation, the mergeSort
method first checks if the input array has a length of 1 or less. If so, it returns the array as is, as the base case has been reached.
If the input array has more than one element, the method divides the array into two halves, recursively sorts the left and right subarrays, and then merges the sorted subarrays back together.
The merge
method is responsible for merging the sorted left and right subarrays into a single sorted array.
By handling the base case correctly, the Merge Sort algorithm can efficiently sort the input array, even for large datasets.