|
| 1 | +package com.learn.datastructure; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +public class MergesortAlgo { |
| 6 | + |
| 7 | + public static void main(String[] args) { |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | + int size; |
| 12 | + System.out.print("Enter the size of the array: "); |
| 13 | + Scanner sc = new Scanner(System.in); |
| 14 | + size = sc.nextInt(); |
| 15 | + |
| 16 | + int[] arr = new int[size]; |
| 17 | + |
| 18 | + System.out.print("Enter the values of the data set: "); |
| 19 | + for(int i=0; i<size; i++) |
| 20 | + arr[i] = sc.nextInt(); |
| 21 | + |
| 22 | + System.out.print("The data before sorting is: "); |
| 23 | + printData(arr); |
| 24 | + |
| 25 | + mergeSort(arr, 0, arr.length-1); |
| 26 | + |
| 27 | + System.out.print("The data after sorting is: "); |
| 28 | + printData(arr); |
| 29 | + |
| 30 | + |
| 31 | + } |
| 32 | + |
| 33 | + public static void merge(int[] arr, int left, int mid, int right) { |
| 34 | + |
| 35 | + // Find the sizes |
| 36 | + int n1 = (mid - left) + 1; |
| 37 | + int n2 = right - mid; |
| 38 | + |
| 39 | + // Create the temp arrays |
| 40 | + int[] L = new int[n1]; |
| 41 | + int[] R = new int[n2]; |
| 42 | + |
| 43 | + // Copy the data |
| 44 | + for(int i=0; i<n1; i++) |
| 45 | + L[i] = arr[left + i]; |
| 46 | + for(int i=0; i<n2; i++) |
| 47 | + R[i] = arr[(mid+1) + i] ; |
| 48 | + |
| 49 | + // MERGE |
| 50 | + |
| 51 | + // initial indices |
| 52 | + int i=0; int j=0; |
| 53 | + int k = left; |
| 54 | + |
| 55 | + while(i<n1 && j<n2) { |
| 56 | + if(L[i] <= R[j]) { |
| 57 | + arr[k] = L[i]; |
| 58 | + i++; |
| 59 | + } else { |
| 60 | + arr[k] = R[j]; |
| 61 | + j++; |
| 62 | + } |
| 63 | + k++; |
| 64 | + } |
| 65 | + // Copy the remaining data |
| 66 | + while(i < n1) { |
| 67 | + arr[k] = L[i]; |
| 68 | + i++; k++; |
| 69 | + } |
| 70 | + while(j < n2) { |
| 71 | + arr[k] = R[j]; |
| 72 | + j++; k++; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + public static void mergeSort(int[] arr, int start, int end) { |
| 77 | + if(start < end) { |
| 78 | + int mid = (start + end) / 2; |
| 79 | + |
| 80 | + // Sort the left and right data |
| 81 | + mergeSort(arr, start, mid); |
| 82 | + mergeSort(arr, mid+1, end); |
| 83 | + |
| 84 | + merge(arr, start, mid, end); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + public static void printData(int[] arr) { |
| 89 | + int n = arr.length; |
| 90 | + for (int j : arr) System.out.print(j + " "); |
| 91 | + System.out.println(); |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | + |
0 commit comments