Implementing Merge Sort in Java
Now that we have a solid understanding of the Merge Sort algorithm and the merge operation, let's dive into the implementation of Merge Sort in Java.
Merge Sort Algorithm Implementation
The Merge Sort algorithm can be implemented in Java using the following steps:
- Define a
mergeSort
method that takes an input array.
- If the array has more than one element, divide it into two halves.
- Recursively call the
mergeSort
method on the left and right halves.
- Merge the sorted left and right halves using the
merge
method.
Here's the Java code that implements the Merge Sort algorithm:
public static void mergeSort(int[] arr) {
if (arr.length > 1) {
int mid = arr.length / 2;
int[] left = Arrays.copyOfRange(arr, 0, mid);
int[] right = Arrays.copyOfRange(arr, mid, arr.length);
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
}
private static void merge(int[] arr, int[] left, int[] right) {
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < left.length) {
arr[k++] = left[i++];
}
while (j < right.length) {
arr[k++] = right[j++];
}
}
Let's break down the code:
- The
mergeSort
method takes an input array arr
.
- If the array has more than one element, it is divided into two halves using the
mid
variable.
- The
left
and right
subarrays are created using Arrays.copyOfRange
.
- The
mergeSort
method is recursively called on the left
and right
subarrays.
- The
merge
method is called to combine the sorted left
and right
subarrays back into the original arr
.
The merge
method is responsible for merging the two sorted subarrays by comparing their elements and placing them in the correct order in the final array.
Time Complexity
The time complexity of the Merge Sort algorithm is O(n log n), which makes it an efficient choice for sorting large datasets. The divide-and-conquer approach used in Merge Sort ensures that the algorithm scales well with the size of the input.
By understanding the implementation of Merge Sort in Java, you can effectively use this algorithm to sort arrays and solve various sorting-related problems.