Skip to content
This repository has been archived by the owner on Oct 14, 2021. It is now read-only.

Merge Sort in java #540

Merged
merged 1 commit into from
Oct 12, 2021
Merged
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
53 changes: 53 additions & 0 deletions Programming/Java/MergeSort/MergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package Programming.Java.MergeSort;

public class MergeSort {

public static void merge(int[] arr, int l, int mid, int r) {
int[] b = new int[arr.length];
int i = l;
int j = mid + 1;
int k = l;
while (i <= mid && j <= r) {
if (arr[i] < arr[j]) {
b[k] = arr[i];
i++;
} else {
b[k] = arr[j];
j++;
}
k++;
}
if (i > mid) {
while (j <= r) {
b[k] = arr[j];
k++;
j++;
}
} else {
while (i <= mid) {
b[k] = arr[i];
k++;
i++;
}
}
for (k = l; k <= r; k++) {
arr[k] = b[k];
}
}

public static void mergeSort(int[] arr, int l, int r) {
if (l < r) {
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
}

public static void main(String[] args) {
int[] arr = { 73, 188, 894, 915, 940, 616, 900, 548 };
mergeSort(arr, 0, arr.length - 1);
for (int j : arr)
System.out.print(j + " ");
}
}