diff --git a/Kundan-Kumar-Sharma/Java Implementation of Merge Sort b/Kundan-Kumar-Sharma/Java Implementation of Merge Sort new file mode 100644 index 000000000..2d8b32e4c --- /dev/null +++ b/Kundan-Kumar-Sharma/Java Implementation of Merge Sort @@ -0,0 +1,51 @@ +### Kundan Kumar Sharma +- Location: India +- Github: https://github.com/kundankumarsharma9 +*** + + +public class MergeSort { + + public static void mergeSort(int[] arr) { + if (arr.length < 2) return; + int mid = arr.length / 2; + int[] left = new int[mid]; + int[] right = new int[arr.length - mid]; + + for (int i = 0; i < mid; i++) left[i] = arr[i]; + for (int i = mid; i < arr.length; i++) right[i - mid] = arr[i]; + + System.out.println("Dividing: " + arrayToString(arr)); + mergeSort(left); + mergeSort(right); + merge(arr, left, right); + System.out.println("Merging: " + arrayToString(arr)); + } + + public 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++]; + } + + public static String arrayToString(int[] arr) { + StringBuilder sb = new StringBuilder("["); + for (int i = 0; i < arr.length; i++) { + sb.append(arr[i]); + if (i < arr.length - 1) sb.append(", "); + } + sb.append("]"); + return sb.toString(); + } + + public static void main(String[] args) { + int[] arr = {38, 27, 43, 3, 9, 82, 10}; + System.out.println("Original array: " + arrayToString(arr)); + mergeSort(arr); + System.out.println("Sorted array: " + arrayToString(arr)); + } +}