import java.util.Scanner; public class MergeSort { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of elements in the array: "); int n = scanner.nextInt(); int[] array = new int[n]; System.out.println("Enter the elements of the array:"); for (int i = 0; i < n; i++) { array[i] = scanner.nextInt(); } System.out.println("Unsorted Array:"); printArray(array); mergeSort(array, 0, array.length - 1); System.out.println("\nSorted Array:"); printArray(array); scanner.close(); } public static void mergeSort(int[] array, int left, int right) { if (left < right) { int mid = (left + right) / 2; // Sort first and second halves mergeSort(array, left, mid); mergeSort(array, mid + 1, right); // Merge the sorted halves merge(array, left, mid, right); } } public static void merge(int[] array, int left, int mid, int right) { int n1 = mid - left + 1; int n2 = right - mid; // Temporary arrays int[] leftArray = new int[n1]; int[] rightArray = new int[n2]; // Copy data to temporary arrays System.arraycopy(array, left, leftArray, 0, n1); System.arraycopy(array, mid + 1, rightArray, 0, n2); int i = 0, j = 0; int k = left; // Merge the temporary arrays back into 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 while (i < n1) { array[k] = leftArray[i]; i++; k++; } // Copy remaining elements of rightArray while (j < n2) { array[k] = rightArray[j]; j++; k++; } } public static void printArray(int[] array) { for (int num : array) { System.out.print(num + " "); } System.out.println(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter