Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Java Implementation of Merge Sort #2977

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Kundan-Kumar-Sharma/Java Implementation of Merge Sort
Original file line number Diff line number Diff line change
@@ -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));
}
}