public class MergeSort {
// Function to perform merge sort
public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
// Find the middle point to divide the array into two halves
int middle = (left + right) / 2;
// Recursively sort the first and second halves
mergeSort(array, left, middle);
mergeSort(array, middle + 1, right);
// Merge the sorted halves
merge(array, left, middle, right);
}
}
// Function to merge two halves
public static void merge(int[] array, int left, int middle, int right) {
// Sizes of the two subarrays to merge
int n1 = middle - left + 1;
int n2 = right - middle;
// Temporary arrays
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
// Copy data to temporary arrays
for (int i = 0; i < n1; i++)
leftArray[i] = array[left + i];
for (int j = 0; j < n2; j++)
rightArray[j] = array[middle + 1 + j];
// Initial indexes of the subarrays
int i = 0, j = 0;
int k = left; // Initial index of merged subarray
// Merge the temp arrays back into the original array
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}
// Copy remaining elements of leftArray, if any
while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}
// Copy remaining elements of rightArray, if any
while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
public static void main(String[] args) {
int[] array = { 12, 11, 13, 5, 6, 7 };
int n = array.length;
mergeSort(array, 0, n - 1);
System.out.println("Sorted array:");
for (int value : array) {
System.out.print(value + " ");
}
}
}